OR36 链表的回文结构

描述

对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。

给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。

测试样例:

复制代码
1->2->2->1
复制代码
返回:true

思路:找到链表的中间节点(偶数个的话取右边那个)然后把从中间节点开始反转链表然后在用反转后的链表和反转的前半部分的链表比

反转链表和快慢指针

cpp 复制代码
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
typedef struct ListNode LN;

class PalindromeList {
public:
    LN* reverList(LN* head)
    {
        if(head==NULL)
        {
            return head;
        }
        LN* n1,*n2,*n3;
        n1=NULL;
        n2=head;
        n3=head->next;
        while(n2)
        {
            n2->next=n1;
            n1=n2;
            n2=n3;
            if(n3)
            {
                n3=n3->next;
            }
        }
        return n1;
    }
    LN* midNode(LN* head)
    {
        LN* fast,* slow;
        fast=slow=head;
        while(fast && fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        return slow;
    }
    bool chkPalindrome(ListNode* A) {
        // write code here
        LN* midnode=midNode(A);
        LN* remid=reverList(midnode);
        while(A && remid)
        {
            if(A->val !=remid->val)
            {
                return false;
            }
            A=A->next;
            remid=remid->next;
        }
        return true;
    }
};
相关推荐
iAkuya2 小时前
(leetcode)力扣100 34合并K个升序链表(排序,分治合并,优先队列)
算法·leetcode·链表
我是小狼君2 小时前
【查找篇章之三:斐波那契查找】斐波那契查找:用黄金分割去“切”数组
数据结构·算法
放荡不羁的野指针2 小时前
leetcode150题-字符串
数据结构·算法·leetcode
bubiyoushang8883 小时前
MATLAB比较SLM、PTS和Clipping三种算法对OFDM系统PAPR的抑制效果
数据结构·算法·matlab
灵哎惹,凌沃敏3 小时前
FreeRTOS 任务上下文切换核心函数:xPortPendSVHandler详解
c语言·arm开发
C雨后彩虹3 小时前
计算误码率
java·数据结构·算法·华为·面试
不染尘.4 小时前
进程切换和线程调度
linux·数据结构·windows·缓存
ada7_4 小时前
LeetCode(python)22.括号生成
开发语言·数据结构·python·算法·leetcode·职场和发展
喵了meme4 小时前
C语言实战练习
c语言·开发语言
White_Can4 小时前
《C++11:列表初始化》
c语言·开发语言·c++·vscode·stl