Skip to content

Commit 85da8e3

Browse files
committed
Solve 234 with C++ and O(1) space!
1 parent d6e655a commit 85da8e3

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
/*
2+
* Author: illuz <iilluzen[at]gmail.com>
3+
* File: AC_reverse_1.cpp
4+
* Create Date: 2015-07-29 11:49:16
5+
* Descripton:
6+
*/
7+
8+
9+
#include <bits/stdc++.h>
10+
11+
using namespace std;
12+
const int N = 0;
13+
14+
// Definition for singly-linked list.
15+
struct ListNode {
16+
int val;
17+
ListNode *next;
18+
ListNode(int x) : val(x), next(NULL) {}
19+
};
20+
21+
class Solution {
22+
public:
23+
bool isPalindrome(ListNode* head) {
24+
int sz = get_length(head);
25+
if (sz < 2)
26+
return true;
27+
28+
// reverse half
29+
ListNode *new_head = reverseBetween(head, 1, sz / 2);
30+
31+
ListNode *head1 = new_head, *head2;
32+
// now the head is point to (sz/2)th node
33+
if (sz % 2 == 1) {
34+
head2 = head->next->next;
35+
} else {
36+
head2 = head->next;
37+
}
38+
bool ok = true;
39+
for (int i = 0; i < sz / 2; ++i) {
40+
if (head1->val != head2->val) {
41+
ok = false;
42+
break;
43+
}
44+
head1 = head1->next;
45+
head2 = head2->next;
46+
}
47+
48+
// reverse half again
49+
reverseBetween(new_head, 1, sz / 2);
50+
return ok;
51+
}
52+
53+
private:
54+
int get_length(ListNode* head) {
55+
int sz = 0;
56+
while (head) {
57+
++sz;
58+
head = head->next;
59+
}
60+
return sz;
61+
}
62+
63+
// these codes are the same as https://github.com/illuz/leetcode/blob/master/solutions/092.Reverse_Linked_List_II/AC_simulate_n.cpp
64+
ListNode *reverseBetween(ListNode *head, int m, int n) {
65+
ListNode *mhead = new ListNode(0), *prev, *cur;
66+
mhead->next = head; // because m will be 0
67+
for (int i = 0; i < m - 1; i++) {
68+
mhead = mhead->next;
69+
}
70+
71+
prev = mhead->next;
72+
cur = prev->next;
73+
for (int i = m; i < n; i++) {
74+
prev->next = cur->next;
75+
cur->next = mhead->next;
76+
mhead->next = cur;
77+
cur = prev->next;
78+
}
79+
return m == 1 ? mhead->next : head;
80+
}
81+
};
82+
83+
int main() {
84+
Solution s;
85+
ListNode l1(1);
86+
ListNode l2(2);
87+
ListNode l3(2);
88+
ListNode l4(1);
89+
ListNode l5(2);
90+
ListNode l6(1);
91+
cout << s.isPalindrome(&l1) << endl;
92+
l1.next = &l2;
93+
cout << s.isPalindrome(&l1) << endl;
94+
l2.next = &l3;
95+
cout << s.isPalindrome(&l1) << endl;
96+
l3.next = &l4;
97+
cout << s.isPalindrome(&l1) << endl;
98+
l4.next = &l5;
99+
cout << s.isPalindrome(&l1) << endl;
100+
l5.next = &l6;
101+
cout << s.isPalindrome(&l1) << endl;
102+
return 0;
103+
}
104+

0 commit comments

Comments
 (0)