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;
    }
};
相关推荐
好易学·数据结构8 小时前
可视化图解算法56:岛屿数量
数据结构·算法·leetcode·力扣·回溯·牛客网
Ashlee_code14 小时前
裂变时刻:全球关税重构下的券商交易系统跃迁路线图(2025-2027)
java·大数据·数据结构·python·云原生·区块链·perl
闻缺陷则喜何志丹14 小时前
【带权的并集查找】 P9235 [蓝桥杯 2023 省 A] 网络稳定性|省选-
数据结构·c++·蓝桥杯·洛谷·并集查找
jie*15 小时前
python(one day)——春水碧于天,画船听雨眠。
开发语言·数据结构·python·算法·线性回归
草莓熊Lotso16 小时前
【LeetCode刷题指南】--数组串联,合并两个有序数组,删除有序数组中的重复项
c语言·数据结构·其他·刷题
weixin_4196583116 小时前
数据结构之B-树
java·数据结构·b树
H_HX_xL_L16 小时前
数据结构的算法分析与线性表<1>
数据结构·算法
overFitBrain16 小时前
数据结构-2(链表)
数据结构
xienda16 小时前
数据结构排序算法总结(C语言实现)
数据结构·算法·排序算法
科大饭桶16 小时前
数据结构自学Day8: 堆的排序以及TopK问题
数据结构·c++·算法·leetcode·二叉树·c