-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path234_palindromelinkedlist.cpp
44 lines (36 loc) · 1.01 KB
/
234_palindromelinkedlist.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
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return true;
}
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* reversed = reverseList(slow);
ListNode* curr = head;
while (reversed != nullptr) {
if (curr->val != reversed->val) {
return false; // Not a palindrome
}
curr = curr->next;
reversed = reversed->next;
}
return true; // Palindrome
}
private:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
};