[InterviewBit] Palindrome List

Palindrome List

  • Time :
  • Space :
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
43
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* find(ListNode* A) {
ListNode* slow = A;
ListNode* fast = A;
while(fast->next and fast->next->next) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
ListNode* reverse(ListNode* A) {
ListNode* dummy = new ListNode(-1);
ListNode* runner = A;
while(runner) {
ListNode* next = runner->next;
runner->next = dummy->next;
dummy->next = runner;
runner = next;
}
return dummy->next;
}
int Solution::lPalin(ListNode* A) {
if(A->next == NULL) return true;
ListNode* mid = find(A);
ListNode* cut = mid->next;
mid->next = NULL;
ListNode* rev = reverse(cut);
ListNode* runner = A;
while(rev) {
if(rev->val != runner->val) return false;
rev = rev->next;
runner = runner->next;
}
return true;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/12/PS/interviewbit/palindrome-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.