-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathLC0234.cpp
executable file
·51 lines (44 loc) · 941 Bytes
/
LC0234.cpp
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
44
45
46
47
48
49
50
51
/*
Problem Statement: https://leetcode.com/problems/palindrome-linked-list/
Time: O(n)
Space: O(1)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *tail, *beg, *mid, *end;
beg = head;
mid = middle_node(head);
tail = end = reverse_list(mid);
while (beg != mid) {
if (beg->val != end->val) {
reverse_list(tail);
return false;
}
beg = beg->next;
end = end->next;
}
reverse_list(tail);
return true;
}
ListNode* middle_node(ListNode* head) {
ListNode *slow, *fast;
slow = fast = head;
// floyd's cycle-finding algorithm
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* reverse_list(ListNode* head) {
ListNode *next, *prev = nullptr;
while (head) {
next = head->next;
head->next = prev;
prev = exchange(head, next);
}
return prev;
}
};