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;
    }
};
相关推荐
Sheep Shaun12 小时前
STL中的unordered_map和unordered_set:哈希表的快速通道
开发语言·数据结构·c++·散列表
optimistic_chen12 小时前
【Redis 系列】常用数据结构---String类型
数据结构·数据库·redis·缓存·string
wen__xvn12 小时前
代码随想录算法训练营DAY1第一章 数组part01
数据结构·算法·leetcode
爱编码的傅同学12 小时前
【程序地址空间】页表的映射方式
c语言·数据结构·c++·算法
Mintopia12 小时前
🧠 从零开始:纯手写一个支持流式 JSON 解析的 React Renderer
前端·数据结构·react.js
造夢先森13 小时前
常见数据结构及算法
数据结构·算法·leetcode·贪心算法·动态规划
iAkuya13 小时前
(leetcode)力扣100 29删除链表的倒数第 N 个结点(双指针)
算法·leetcode·链表
良木生香13 小时前
【数据结构-初阶】二叉树---链式存储
c语言·数据结构·c++·算法·蓝桥杯·深度优先
长安er1 天前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
粉红色回忆1 天前
用链表实现了简单版本的malloc/free函数
数据结构·c++