单链表---回文结构

判断某一个单链表是否是回文结构,是返回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;
    }
};
相关推荐
炽烈小老头1 天前
【每天学习一点算法 2025/12/18】对称二叉树
学习·算法
蒙奇D索大1 天前
【数据结构】考研408 | 开放定址法精讲:连续探测的艺术与代价
数据结构·笔记·考研·改行学it
子夜江寒1 天前
pandas基础操作
学习·pandas
User_芊芊君子1 天前
【LeetCode经典题解】:二叉树转字符串递归解法的核心逻辑与代码解剖
算法·leetcode·职场和发展
EveryPossible1 天前
宽度撑开容器
学习
程序员zgh1 天前
C++常用设计模式
c语言·数据结构·c++·设计模式
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——计算右侧小于当前元素的个数
算法·leetcode·排序算法·职业发展
深蓝海拓1 天前
PySide6从0开始学习的笔记(八) 控件(Widget)之QSlider(滑动条)
笔记·python·qt·学习·pyqt
鹿角片ljp1 天前
力扣110.平衡二叉树-递归
数据结构·算法·leetcode
一起养小猫1 天前
《Java数据结构与算法》第四篇(三)二叉树遍历详解_CSDN文章
java·开发语言·数据结构