/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
//Time Limit Exceeded
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
vector<ListNode*> v;
while(head){
v.push_back(head);
head=head->next;
}
for(int i= 0,j=v.size()-1; i<j;){
if(v[i]->val != v[j]->val) return false;
}
return true;
}
};
*/
// 1. revsercie sencond part
// 2. compare the first part == secondpart
// 3. how to get the middle position, slow and fast
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
ListNode* slow = head;
ListNode* fast = head;
while(fast->next != NULL && fast->next->next !=NULL){
slow = slow->next;
fast = fast->next->next;
}
ListNode* temp = reverseList(slow->next);
slow->next = temp;
slow = slow->next;
temp = head;
while(slow){
if(slow->val != temp->val) return false;
slow = slow->next;
temp = temp->next;
}
return true;
}
private:
ListNode* reverseList(ListNode* head)
{
ListNode* pre = NULL;
ListNode* temp = NULL;
while(head){
temp = head->next;
head->next = pre;
pre = head;
head = temp;
}
return pre;
}
};
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
//Time Limit Exceeded
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
vector<ListNode*> v;
while(head){
v.push_back(head);
head=head->next;
}
for(int i= 0,j=v.size()-1; i<j;){
if(v[i]->val != v[j]->val) return false;
}
return true;
}
};
*/
// 1. revsercie sencond part
// 2. compare the first part == secondpart
// 3. how to get the middle position, slow and fast
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
ListNode* slow = head;
ListNode* fast = head;
while(fast->next != NULL && fast->next->next !=NULL){
slow = slow->next;
fast = fast->next->next;
}
ListNode* temp = reverseList(slow->next);
slow->next = temp;
slow = slow->next;
temp = head;
while(slow){
if(slow->val != temp->val) return false;
slow = slow->next;
temp = temp->next;
}
return true;
}
private:
ListNode* reverseList(ListNode* head)
{
ListNode* pre = NULL;
ListNode* temp = NULL;
while(head){
temp = head->next;
head->next = pre;
pre = head;
head = temp;
}
return pre;
}
};