[LeetCode] Palindrome Linked List

234. Palindrome Linked List

Given the head of a singly linked list, return true if it is a palindrome.

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

  • Time : O(n)
  • Space : O(1)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head->next) return true;
if(!head->next->next) return head->next->val == head->val;

ListNode *mid = head, *tail = head, *prev = NULL, *nxt;
while(tail->next and tail->next->next) {
tail = tail->next->next;
nxt = mid->next; //next mid
mid->next = prev; //reverse
prev = mid;
mid = nxt;
}
//if size is odd move forward
if(!tail->next) mid = mid->next;
else {
nxt = mid->next; //next mid
mid->next = prev; //reverse
prev = mid;
mid = nxt;
}

while(mid != NULL and prev != NULL) {
if(mid->val != prev->val) return false;
mid = mid->next;
prev = prev->next;
}

return !mid and !prev;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/palindrome-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.