-
Notifications
You must be signed in to change notification settings - Fork 288
/
Copy pathAC_reverse_1.cpp
104 lines (91 loc) · 2.45 KB
/
AC_reverse_1.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_reverse_1.cpp
* Create Date: 2015-07-29 11:49:16
* Descripton:
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool isPalindrome(ListNode* head) {
int sz = get_length(head);
if (sz < 2)
return true;
// reverse half
ListNode *new_head = reverseBetween(head, 1, sz / 2);
ListNode *head1 = new_head, *head2;
// now the head is point to (sz/2)th node
if (sz % 2 == 1) {
head2 = head->next->next;
} else {
head2 = head->next;
}
bool ok = true;
for (int i = 0; i < sz / 2; ++i) {
if (head1->val != head2->val) {
ok = false;
break;
}
head1 = head1->next;
head2 = head2->next;
}
// reverse half again
reverseBetween(new_head, 1, sz / 2);
return ok;
}
private:
int get_length(ListNode* head) {
int sz = 0;
while (head) {
++sz;
head = head->next;
}
return sz;
}
// these codes are the same as https://github.com/illuz/leetcode/blob/master/solutions/092.Reverse_Linked_List_II/AC_simulate_n.cpp
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode *mhead = new ListNode(0), *prev, *cur;
mhead->next = head; // because m will be 0
for (int i = 0; i < m - 1; i++) {
mhead = mhead->next;
}
prev = mhead->next;
cur = prev->next;
for (int i = m; i < n; i++) {
prev->next = cur->next;
cur->next = mhead->next;
mhead->next = cur;
cur = prev->next;
}
return m == 1 ? mhead->next : head;
}
};
int main() {
Solution s;
ListNode l1(1);
ListNode l2(2);
ListNode l3(2);
ListNode l4(1);
ListNode l5(2);
ListNode l6(1);
cout << s.isPalindrome(&l1) << endl;
l1.next = &l2;
cout << s.isPalindrome(&l1) << endl;
l2.next = &l3;
cout << s.isPalindrome(&l1) << endl;
l3.next = &l4;
cout << s.isPalindrome(&l1) << endl;
l4.next = &l5;
cout << s.isPalindrome(&l1) << endl;
l5.next = &l6;
cout << s.isPalindrome(&l1) << endl;
return 0;
}