描述
对于一个链表,请设计一个时间复杂度为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) {}
};*/
struct ListNode* middleNode(struct ListNode* head){
if(head==NULL)
return NULL;
struct ListNode *fast=head;
struct ListNode *slow=head;
while(fast && fast->next){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
struct ListNode* reverseList(struct ListNode* head){
//当为空链表的时候:
if(head==NULL)
return NULL;
struct ListNode *n1=NULL;
struct ListNode *n2=head;
struct ListNode *n3=head->next;
while(n2){
//反转
n2->next=n1;
//迭代
n1=n2;
n2=n3;
if(n3)
n3=n3->next;
}
return n1;
}
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
// write code here
struct ListNode* mid=middleNode(A);
struct ListNode* rHead=reverseList(A);
struct ListNode* curA=A;
struct ListNode* curR=rHead;
while(curA && curR){
if(curA->val!=curR->val){
return false;
}
else{
curA=curA->next;
curR=curR->next;
}
}
return true;
}
};
当然在笔试的时候我们没有过多的时间的时候,也可以用一些巧的方法,能通过用例测试但可能不是面试官期待的结果的方法:糊弄大法
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
int a[900];
struct ListNode* cur=A;
int n=0;
while(cur){
a[n++]=cur->val;
cur=cur->next;
}
int left=0,right=n-1;
while(left<right){
if(a[left]!=a[right]){
return false;
}
left++;
right--;
}
return true;
}
};