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;
    }
};
相关推荐
努力努力再努力wz21 小时前
【Linux网络系列】:TCP 的秩序与策略:揭秘传输层如何从不可靠的网络中构建绝对可靠的通信信道
java·linux·开发语言·数据结构·c++·python·算法
重生之后端学习1 天前
78. 子集
java·数据结构·算法·职场和发展·深度优先
kronos.荒1 天前
滑动窗口+哈希表:最小覆盖子串
数据结构·python·散列表
wostcdk1 天前
筛质数汇总
数据结构·算法
qq_454245031 天前
BuildTemplateGraph 函数深度解析:动态节点图构建的架构设计与核心价值
数据结构·c#
qq_454245031 天前
SkeletonFlow:基于组合子逻辑与范畴论的数据流处理框架
数据结构·c#
逆境不可逃1 天前
【春节篇】LeetCode 热题 100 之 238.除了自身以外数组的乘积
数据结构·算法·leetcode
散峰而望1 天前
【算法竞赛】堆和 priority_queue
开发语言·数据结构·c++·算法·贪心算法·动态规划·推荐算法
重生之后端学习1 天前
46. 全排列
数据结构·算法·职场和发展·深度优先·图论
wostcdk1 天前
数论学习1
数据结构·学习·算法