-
Notifications
You must be signed in to change notification settings - Fork 0
/
0234_Palindrome_Linked_List.cpp
40 lines (38 loc) · 1.12 KB
/
0234_Palindrome_Linked_List.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
/**
* 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) {}
* };
*/
#pragma GCC optimize("Ofast","inline","ffast-math","unroll-loops","no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native","f16c")
class Solution {
public:
bool isPalindrome(ListNode* head) {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
ListNode* slow = head;
ListNode* fast = head->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* pre = nullptr;
ListNode* cur = slow->next;
while (cur) {
ListNode* t = cur->next;
cur->next = pre;
pre = cur;
cur = t;
}
while (pre) {
if (pre->val != head->val) return false;
pre = pre->next;
head = head->next;
}
return true;
}
};