单链表---回文结构

判断某一个单链表是否是回文结构,是返回true、不是返回false。

所谓的回文结构,就是类似对称结构:

对于奇数与偶数个结点均是如此。

那么就有思路:①找到链表的中间结点②逆置后半部分或前半部分③比较两者

①找中间结点:

cpp 复制代码
    ListNode* slow , *fast;
    fast = slow = head;
    while(fast&&fast->next)
    {
        fast=fast->next->next;
        slow=slow->next;
    }
    ListNode* mid = slow;

②逆置后半部分

可以使用三指针的方式进行逆置,也可以如上图所示创建一个指针变量midhead来头插。

cpp 复制代码
    //三指针逆置
    ListNode* mid = slow;
    while(mid->next)
    {
        ListNode* midnext = mid->next;
        ListNode* midnextnext = midnext->next;
        midnext->next = mid;
        mid = midnext;
    }
cpp 复制代码
    //逆置mid后的链表,采用头插
    ListNode* midhead = NULL;
    while(mid)
    {
        ListNode* midnext = mid->next;
        mid->next = midhead;
        midhead = mid;
        mid = midnext;
    }

③遍历比较两个链表同位置处的值

cpp 复制代码
    while(midhead&&head)
    {
        if(midhead->val!=head->val)
            return false;
        midhead=midhead->next;
        head=head->next;
    }
    return true;

整体代码如下:

cpp 复制代码
public:
    bool chkPalindrome(ListNode* head) {
        ListNode* slow , *fast;
        fast = slow = head;
        while(fast&&fast->next)
        {
            fast=fast->next->next;
            slow=slow->next;
        }
        ListNode* mid = slow;
        while(mid->next)
        {
            ListNode* midnext = mid->next;
            ListNode* midnextnext = midnext->next;
            midnext->next = mid;
            mid = midnext;
        }
        while(mid&&head)
        {
            if(mid->val!=head->val)
                return false;
            mid=mid->next;
            head=head->next;
        }
        return true;
    }
};
相关推荐
我搞slam11 分钟前
有效的括号--leetcode
linux·算法·leetcode
消失的旧时光-194312 分钟前
c语言 内存管理(malloc, calloc, free)
c语言·开发语言
degen_16 分钟前
注册协议通知
c语言·笔记
jamesge201021 分钟前
zookeeper学习笔记
笔记·学习·zookeeper·1024程序员节
Century_Dragon26 分钟前
比亚迪秦新能源汽车动力系统拆装与检测实训MR软件介绍
学习
Yupureki1 小时前
从零开始的C++学习生活 19:C++复习课(5.4w字全解析)
c语言·数据结构·c++·学习·1024程序员节
wangqiaowq1 小时前
PAIMON 学习
学习
笨鸟笃行2 小时前
百日挑战-单词篇(第九天)
学习
ゞ 正在缓冲99%…2 小时前
leetcode1312.让字符串成为回文串的最少插入次数
数据结构·算法·leetcode·动态规划·记忆化搜索
七夜zippoe2 小时前
Rust `std::iter` 深度解析:`Iterator` Trait、适配器与性能
开发语言·算法·rust