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