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;
    }
};
相关推荐
ghie909021 小时前
MATLAB自适应子空间辨识工具箱
数据结构·算法·matlab
松涛和鸣1 天前
25、数据结构:树与二叉树的概念、特性及递归实现
linux·开发语言·网络·数据结构·算法
獭.獭.1 天前
C++ -- 二叉搜索树
数据结构·c++·算法·二叉搜索树
im_AMBER1 天前
Leetcode 67 长度为 K 子数组中的最大和 | 可获得的最大点数
数据结构·笔记·学习·算法·leetcode
buyue__1 天前
C++实现数据结构——链表
数据结构·c++·链表
Ayanami_Reii1 天前
进阶数据结构应用-SPOJ 3267 D-query
数据结构·算法·线段树·主席树·持久化线段树
Genevieve_xiao1 天前
【数据结构与算法】【xjtuse】面向考纲学习(下)
java·数据结构·学习·算法
仰泳的熊猫1 天前
1031 Hello World for U
数据结构·c++·算法·pat考试
liu****1 天前
12.C语言内存相关函数
c语言·开发语言·数据结构·c++·算法
FMRbpm1 天前
栈练习--------从链表中移除节点(LeetCode 2487)
数据结构·c++·leetcode·链表·新手入门