问题描述:
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
分析:要求O(n)的时间复杂度,以及O(1)的空间。那么就不能新开辟空间,为了满足要求,思想是:将链表截为两段,第一段是顺序的,第二段是反序的,然后从两端开始遍历。
代码如下:16ms
bool isPalindrome(struct ListNode* head) {
if(!head)
return true;
//count the length
struct ListNode *tmp = head;
struct ListNode *tail = NULL;
int length = 0;
//reverse second list
struct ListNode *current,*currentNext,*prev;
while(tmp){
length++;
tail = tmp;//store tail value
tmp = tmp->next;
}
int mid = length/2;//取中间值
if(mid==0)
return true;
tmp = head;
length = 0;
while(tmp){
length++;
if(length==mid){
current = tmp->next;
tmp->next = NULL;
break;
}
tmp = tmp->next;
}
currentNext = current->next;prev = NULL;
if(current!=tail){
while(currentNext!=NULL){
current->next = prev;
tmp = currentNext->next;
prev = current;
current = currentNext;
currentNext = tmp;
}
current->next = prev;
}
//开始比较
while(head&&tail){
if(head->val != tail->val)
return false;
head = head->next;
tail = tail->next;
}
return true;
}