1+ //
2+ // Created by 10578 on 2021/4/1.
3+ //
4+
5+ #include " iostream"
6+ #include " vector"
7+ #include " algorithm"
8+ #include " initializer_list"
9+
10+ using namespace std ;
11+
12+ struct ListNode {
13+ int val;
14+ ListNode *next;
15+
16+ ListNode () : val(0 ), next(nullptr ) {}
17+
18+ ListNode (int x) : val(x), next(nullptr ) {}
19+
20+ ListNode (int x, ListNode *next) : val(x), next(next) {}
21+
22+ ListNode (std::initializer_list<int > ini) {
23+ ListNode *prev, *curr = this ;
24+ for (auto &&x: ini) {
25+ curr->val = x;
26+ curr->next = new ListNode ();
27+ prev = curr;
28+ curr = curr->next ;
29+ }
30+ prev->next = nullptr ;
31+ }
32+
33+ void print () {
34+ ListNode *curr = this ;
35+ while (curr) {
36+ std::cout << curr->val << " " ;
37+ curr = curr->next ;
38+ }
39+ }
40+ };
41+
42+ class Solution {
43+ public:
44+ bool isPalindrome (ListNode *head) {
45+ if (head->next == nullptr ) {
46+ return true ;
47+ }
48+
49+ // O(1) space complexity
50+ ListNode *mid = head, *tail = head;
51+ while (tail) {
52+ tail = tail->next ;
53+ if (tail && tail->next ) {
54+ mid = mid->next ;
55+ tail = tail->next ;
56+ }
57+ }
58+
59+ ListNode *reversed_tail = mid->next ;
60+ ListNode *curr = reversed_tail->next ;
61+ reversed_tail->next = nullptr ;
62+ ListNode *prev = reversed_tail;
63+ ListNode *next;
64+ while (curr) {
65+ next = curr->next ;
66+ curr->next = prev;
67+ prev = curr;
68+ curr = next;
69+ }
70+
71+ ListNode *reversed_head = prev;
72+ ListNode *rev_curr = reversed_head;
73+ ListNode *for_curr = head;
74+ while (rev_curr) {
75+ if (rev_curr->val != for_curr->val ) {
76+ return false ;
77+ }
78+ rev_curr = rev_curr->next ;
79+ for_curr = for_curr->next ;
80+ }
81+
82+ return true ;
83+ }
84+ };
85+
86+ int main () {
87+ ListNode *head = new ListNode{1 };
88+
89+ Solution s;
90+ cout << s.isPalindrome (head);
91+ }
0 commit comments