Palindrome Linked List
Total Accepted: 31409 Total Submissions: 122659 Difficulty: Easy
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?
思路:
1.快慢指间找到链的中间部分。
2.在1中,慢指针的遍历过程中,还要改变指针的方向,使得最后链可由中间通过指针走到两端末尾。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL){
return true;
}
if(head->next==NULL){
return true;
}else if(head->next->next==NULL){
if(head->next->val==head->val){
return true;
}else{
return false;
}
}
ListNode* p=head;
ListNode* q=head;
ListNode* temp=head;
ListNode* pre=NULL;
while(q->next!=NULL&&q->next->next!=NULL){
q=q->next->next;
temp=p->next;
p->next=pre;
pre=p;
p=temp;
}
if(q->next==NULL){
p=pre;
q=temp->next;
}else{
q=temp->next;
p->next=pre;
}
while(p!=NULL){
if(p->val!=q->val){
return false;
}
p=p->next;
q=q->next;
}
return true;
}
};