Palindrome Linked List

Desicription

Given a singly linked list, determine if it is a palindrome.

Example 1:

1
2
Input: 1->2
Output: false

Example 2:

1
2
Input: 1->2->2->1
Output: true

Follow up:

Could you do it in O(n) time and O(1) space?

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* tmp = nullptr;
bool check(ListNode* p) {
if(nullptr == p) {
return true;
}
bool flag = check(p->next) && (p->val == tmp->val);
tmp = tmp->next;
return flag;
}
public:
bool isPalindrome(ListNode* head) {
tmp = head;
return check(head);
}
};