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;
    }
};
相关推荐
Qhumaing7 分钟前
C++学习:【PTA】数据结构 7-2 实验6-2(图-邻接表)
数据结构·c++·学习
方便面不加香菜9 分钟前
基于顺序表实现通讯录项目
c语言·数据结构
MQLYES1 小时前
03-BTC-数据结构
数据结构·算法·哈希算法
无限进步_1 小时前
【数据结构&C语言】对称二叉树的递归之美:镜像世界的探索
c语言·开发语言·数据结构·c++·算法·github·visual studio
im_AMBER2 小时前
Leetcode 98 从链表中移除在数组中存在的节点
c++·笔记·学习·算法·leetcode·链表
不会c嘎嘎2 小时前
C++ 进阶:从理论到手撕 Unordered 系列容器(哈希表)
数据结构·哈希算法·散列表
nice_lcj5203 小时前
数据结构之堆:从概念到应用全解析(附TOP-K经典问题)
java·数据结构·算法
漫随流水3 小时前
leetcode算法(429.N叉树的层序遍历)
数据结构·算法·leetcode·二叉树
漫随流水3 小时前
leetcode算法(116.填充每个节点的下一个右侧节点指针)
数据结构·算法·leetcode·二叉树
橘颂TA4 小时前
【剑斩OFFER】算法的暴力美学——力扣 844 题:比较含退格的字符串
数据结构·c++·算法·力扣·结构与算法