Title
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?
Language C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode* head) {
if(head == NULL || head->next == NULL){//null or only one -> Palindrome
return true;
}
struct ListNode *slow, *fast;
slow = head;
fast = head;
//1,2,3,2,1;1,2,2,1
while(fast != NULL && fast->next != NULL){//find middle; O(n/2)
slow = slow->next;
fast = fast->next->next;
}
if(fast != NULL){//odd
slow = slow->next;
}
struct ListNode *pre;//reverse
pre = NULL;
while(slow != NULL){ //O(n/2)
fast = slow->next;
slow->next = pre;
pre = slow;
slow = fast;
}
slow = head;
while((pre != NULL) && (pre->val == slow->val)){//contrast former with later; O(n/2)
pre = pre->next;
slow = slow->next;
}
if(pre == NULL){
return true;
}
return false;
}
runtime:12ms
思路
- 获取链表的中点,使用龟兔算法的方法,两个指针,一个遍历速度是另外一个的两倍,找到中点;
- 反转链表的后半部分;
- 对比链表的前后两个部分是否一样