题目描述:
对于一个链表,请设计一个时间复杂度为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) {}
};*/
class PalindromeList {
public:
struct ListNode *MiddeNode(struct ListNode *head) //创建一个函数 找中间节点
{
struct ListNode *fast,*slow;
fast=slow=head;
while(fast&&fast->next) //定义快慢指针 找中间节点
{
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
//逆置函数
struct ListNode *reverseList(struct ListNode *head)
{
struct ListNode *newhead=NULL;
struct ListNode *cur=head;
while(cur)
{
struct ListNode *next=cur->next;
cur->next=newhead;
newhead=cur;
cur=next;
}
return newhead;
}
bool chkPalindrome(ListNode* A)
{
// write code here
struct ListNode *Mid= MiddeNode(A);
struct ListNode *Mhead=reverseList(Mid);
while(A&&Mhead)
{
if(A->val==Mhead->val)//遍历链表 看看元素是否相等
{
A=A->next;
Mhead=Mhead->next;
}
else
{
return false;
}
}
return true;
}
};