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;
    }
};
相关推荐
Sam_Deep_Thinking17 小时前
学数据结构到底有什么用
数据结构
py有趣20 小时前
力扣热门100题之和为K的子数组
数据结构·算法·leetcode
hipolymers21 小时前
C语言怎么样?难学吗?
c语言·数据结构·学习·算法·编程
CS创新实验室21 小时前
从“跑得动”到“跑得稳”:深度剖析数据结构究竟是理论点缀还是核心战力?
数据结构
jllllyuz1 天前
MATLAB 蒙特卡洛排队等待模拟程序
数据结构·matlab
自我意识的多元宇宙1 天前
树、森林——树、森林与二叉树的转换(森林转换为二叉树)
数据结构
海清河晏1111 天前
数据结构 | 双循环链表
数据结构·链表
py有趣1 天前
力扣热门100题之编辑距离
数据结构·算法·leetcode
努力努力再努力wz1 天前
【Linux网络系列】万字硬核解析网络层核心:IP协议到IP 分片重组、NAT技术及 RIP/OSPF 动态路由全景
java·linux·运维·服务器·数据结构·c++·python
谭欣辰1 天前
AC自动机:多模式匹配的高效利器
数据结构·c++·算法