单链表---回文结构

判断某一个单链表是否是回文结构,是返回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;
    }
};
相关推荐
wuyk5558 小时前
Keil工具链-第05讲-启动文件与__main到底做了什么
c语言·stm32·单片机·嵌入式硬件·物联网
NEFU_Jyj8 小时前
牛客周赛R168
算法
La Pulga11 小时前
【FreeRTOS源码学习笔记】任务延时列表
笔记·mcu·学习·嵌入式·freertos·实时操作系统
楚山之石12 小时前
【JCO】mpMRI 先行替代 TURBT 初始分期:BladderPath 随机试验让 MIBC 患者提前 45 天得到正确治疗
人工智能·学习·mri·医学影像
likexuec14 小时前
数据结构(2)
数据结构
Navigator_Z16 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
Peter-OK16 小时前
PostgreSQL学习笔记(入门-进阶-精通说明)
笔记·学习·postgresql
承渊政道16 小时前
Linux网络学习【Reactor反应堆模式】
linux·网络·学习·ubuntu·reactor
D e re k ZH16 小时前
C++ 标准库算法全景指南
数据结构·c++·算法