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;
    }
};
相关推荐
祈安_1 天前
C语言内存函数
c语言·后端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David3 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
czy87874753 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237173 天前
C语言-数组练习进阶
c语言·开发语言·算法
qq_454245033 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA3 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc3 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg13 天前
【算法】单调栈和单调队列
数据结构·算法