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;
    }
};
相关推荐
WBluuue13 分钟前
数据结构与算法:有序表(二):跳表
数据结构·c++·算法·skiplist
不好听6131 小时前
深入理解链表:线性数据结构的另一面
javascript·数据结构
x138702859571 小时前
c语言中srtlen(指针使用计算字符长度)、传值和传址调用
c语言·开发语言·算法·visual studio
Queenie_Charlie2 小时前
哈夫曼树
数据结构·c++·哈夫曼树
Shan12054 小时前
经典问题——验证栈序列
数据结构·算法
Aurorar0rua5 小时前
CS50 x 2024 Notes Arrays - 04
c语言·开发语言·学习方法
wuminyu6 小时前
Java世界中StringTable源码剖析
java·linux·c语言·jvm·c++
漂流瓶jz6 小时前
UVA-1606 两亲性分子 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·向量·aoapc·算法竞赛入门经典·atan2·浮点
Navigator_Z6 小时前
LeetCode //C - 1095. Find in Mountain Array
c语言·算法·leetcode
Chen_harmony6 小时前
二、顺序表
数据结构