#1 using stack
time: O(n); space O(n)
/**
* 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) return true;
stack<int> s;
ListNode *cur = head;
int n = 0;
while (cur) {
s.push(cur->val);
cur = cur->next;
n++;
}
//if (n==1) return true;
cur = head;
for (int i = 0; i < n/2; i++) {
int top = s.top();
if (top != cur->val) {
return false;
}
s.pop();
cur = cur->next;
}
return true;
}
};
#2: reverse the linked list
time: O(n); space O(1)
/**
* 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) {
if (!head) return NULL;
ListNode *res = new ListNode(0);
res->next = head;
ListNode *cur = head;
ListNode *next = cur->next;
while (next) {
cur->next = next->next;
next->next = res->next;
res->next = next;
next = cur->next;
}
return res->next;
}
bool isPalindrome(ListNode* head) {
if (!head) return true;
ListNode *cur = head, *pre = head;
int n = 0;
while (cur) {
cur = cur->next;
n++;
}
cur = head;
ListNode* sec = cur;
for (int i = 0; i < n/2; i++) {
pre = sec;
sec = sec->next;
}
if (n%2) sec= sec->next;
sec = reverseList(sec);
ListNode *cur2= sec;
for (int i = 0; i < n/2; i++) {
if (cur->val != cur2->val) {
sec = reverseList(sec);
pre->next = sec;
return false;
}
cur = cur->next;
cur2 = cur2->next;
}
sec = reverseList(sec);
pre->next = sec;
return true;
}
};