234.Palindrome Linked List
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?/**
* 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 || !head->next) return true;
if(!head->next->next) return head->val == head->next->val;
ListNode* slow=head;
ListNode* fast=head;
while(fast->next &&fast->next->next)
{
slow=slow->next;
fast=fast->next->next;
}
//Reverse List
// cout<<slow->val <<endl;
ListNode* pre=head;
ListNode* cur=head->next;
ListNode* tmp=head->next->next;
head->next=NULL;
ListNode* new_head=slow->next;
if(fast->next)
{
slow=slow->next;
while(cur != slow)
{
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
}
else
{
while(cur != slow)
{
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
} cur=pre;
cout<<cur->val<<endl;
while(new_head)
{
if(new_head->val !=cur->val ) return false;
new_head = new_head->next;
cur=cur->next;
}
return true;
}
};Last updated