Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
思路:
用两个指针p,q 都从头开始,每一次,p指针走一步,q指针走两步,这样在q指针走到末尾,或倒数第二个的时候,p指针走到了链表的中间,然后从p的下个链表进行翻转,翻转完成后,将链表的前半段和翻转完的后半段进行以此比较获得结果。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {//这里用的方法是203题的翻转链表的方法,我直接粘了过来
if(head == NULL ||head->next ==NULL)
return head;
ListNode *t,*p,*q;
t = head;
p = head->next;
t->next = NULL;
q = p;
while(q&&p){
q = p->next;
if(q){
p->next = t;
t = p;
p = q;
}
}
p->next = t;
return p;
}
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL)
return true;
ListNode *p = head;
ListNode *q = head;
ListNode *key;
while(q->next != NULL && q->next->next != NULL){
p = p->next;
q = q->next->next;
}
//偶数个,奇数个,均执行这一步
q = reverseList(p->next);
p = head;
while(q->next != NULL){
if(p->val != q->val)
return false;
else{
p = p->next;
q = q->next;
}
}
if(p->val == q->val)
return true;
return false;
}
};