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;
    }
};
相关推荐
任沫1 天前
字符串
数据结构·后端
祈安_1 天前
Java实现循环队列、栈实现队列、队列实现栈
java·数据结构·算法
NineData3 天前
数据库管理工具NineData,一年进化成为数万+开发者的首选数据库工具?
运维·数据结构·数据库
琢磨先生David11 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_4542450311 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝11 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA11 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc11 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg111 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA11 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法