描述
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1
返回:true
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
#include <cstddef>
struct ListNode* midlist(struct ListNode* head)
{
struct ListNode* fast=head;
struct ListNode* slow=head;
while(slow&&slow->next)
{
fast=fast->next;
slow=slow->next->next;
}
return fast;
}
struct ListNode* reverlist(struct ListNode* head)//反向链表
{
if(head==NULL)
return NULL;
struct ListNode* last=NULL;
struct ListNode* cur=head;
struct ListNode* next=cur->next;
while(cur)
{
cur->next=last;
last=cur;
cur=next;
if(next)
next=next->next;
}
return last;
}
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
// write code here
struct ListNode* mid=midlist(A);
struct ListNode* rmid=reverlist(mid);
while(rmid)
{
if(rmid->val!=A->val)
{
return false;
}
else
{
A=A->next;
rmid=rmid->next;
}
}
return true;
}
};
1074

被折叠的 条评论
为什么被折叠?



