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;
    }
};
相关推荐
☆璇38 分钟前
【数据结构】栈和队列
c语言·数据结构
chao_7894 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
秋说4 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法
qqxhb5 小时前
零基础数据结构与算法——第四章:基础算法-排序(中)
数据结构·算法·排序算法·归并·快排·堆排
木叶丸6 小时前
编程开发中,那些你必须掌握的基本概念
前端·数据结构·编程语言
Y1nhl7 小时前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
手握风云-8 小时前
优选算法的链脉之韵:链表专题
数据结构·算法·链表
老虎06279 小时前
数据结构(Java)--位运算
java·开发语言·数据结构
小汉堡编程12 小时前
数据结构——vector数组c++(超详细)
数据结构·c++
雾里看山16 小时前
顺序表VS单链表VS带头双向循环链表
数据结构·链表