OR36 链表的回文结构

目录

一、思路

二、代码

一、思路

找到中间节点

后半部分逆置链表

定义两个指针,一个从头开始出发

一个从中间位置开始出发

但是注意:链表个数可能是奇数或者偶数,需要注意中间节点的计算

二、代码

cs 复制代码
struct ListNode* reverseList(struct ListNode* head) {
    if(head == NULL)
    {
        return NULL;
    }
    struct ListNode *prev = NULL,*cur = head, *next = cur->next;
    while(next)
    {
        if(prev == NULL)
        {
            cur->next = NULL;
        }
        else
        {
            cur->next = prev;
        }
        prev = cur;
        cur = next;
        next = next->next;
    }
    cur->next = prev;
    return cur;
}
#include <asm-generic/errno.h>
class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {
        // write code here
        //找中间节点
        struct ListNode *slow = A, *fast = A;
        while(fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        struct ListNode *mid = slow;
       struct ListNode *rhead = reverseList(slow);

        //比较
        struct ListNode *begin = A;
        while(begin && mid)
        {
            if(begin->val != rhead->val)
                return false;
                begin = begin->next;
                mid = mid->next;
        }
        return true;
    }
};
相关推荐
阿昭L4 小时前
leetcode链表相交
算法·leetcode·链表
xiaolang_8616_wjl9 小时前
c++超级细致的基本框架
开发语言·数据结构·c++·算法
LYFlied10 小时前
【每日算法】LeetCode124. 二叉树中的最大路径和
数据结构·算法·leetcode·面试·职场和发展
yyy(十一月限定版)11 小时前
c语言——栈和队列
java·开发语言·数据结构
xu_yule12 小时前
算法基础-背包问题(01背包问题)
数据结构·c++·算法·01背包
蒙奇D索大12 小时前
【数据结构】考研408 | 伪随机探测与双重散列精讲:散列的艺术与均衡之道
数据结构·笔记·学习·考研
budingxiaomoli12 小时前
分治算法-快排
数据结构·算法
dragoooon3412 小时前
[C++——lesson30.数据结构进阶——「红黑树」]
开发语言·数据结构·c++
蓝色汪洋13 小时前
数码串和oj
数据结构·算法
阿昭L14 小时前
leetcode链表是否有环
算法·leetcode·链表