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;
    }
};
相关推荐
静听山水15 分钟前
Redis核心数据结构-ZSet
数据结构·redis
铉铉这波能秀26 分钟前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
Queenie_Charlie1 小时前
stars(树状数组)
数据结构·c++·树状数组
静听山水1 小时前
Redis核心数据结构-Set
数据结构·数据库·redis
独好紫罗兰1 小时前
对python的再认识-基于数据结构进行-a005-元组-CRUD
开发语言·数据结构·python
wengqidaifeng2 小时前
数据结构(三)栈和队列(上)栈:计算机世界的“叠叠乐”
c语言·数据结构·数据库·链表
静听山水2 小时前
Redis核心数据结构
数据结构·数据库·redis
im_AMBER2 小时前
Leetcode 115 分割链表 | 随机链表的复制
数据结构·学习·算法·leetcode
数智工坊2 小时前
【数据结构-树与二叉树】4.7 哈夫曼树
数据结构
!!!!8132 小时前
蓝桥备赛Day1
数据结构·算法