Skip to content

Commit 5703212

Browse files
author
whd
committedNov 20, 2016
upload
1 parent 978fa3e commit 5703212

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
 

‎ 234 Palindrome Linked List .cpp

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
bool isPalindrome(ListNode* head) {
12+
if (!head) {
13+
return true;
14+
}
15+
auto getLen = [] (ListNode *x) {
16+
int s = 0;
17+
while (x) {
18+
s++;
19+
x = x->next;
20+
}
21+
return s;
22+
};
23+
int len = getLen(head);
24+
auto get = [] (ListNode *x, int k) {
25+
while (k--) {
26+
x = x->next;
27+
}
28+
return x;
29+
};
30+
if (len == 1) {
31+
return true;
32+
}
33+
ListNode *h1 = head, *h2 = get(head, (len + 1) / 2 - 1);
34+
auto next = h2->next;
35+
h2->next = nullptr;
36+
h2 = next;
37+
auto reversed = [] (ListNode *x) {
38+
ListNode *newHead = nullptr;
39+
while (x) {
40+
auto next = x->next;
41+
x->next = newHead;
42+
newHead = x;
43+
x = next;
44+
}
45+
return newHead;
46+
};
47+
h2 = reversed(h2);
48+
for (; h1 && h2; h1 = h1->next, h2 = h2->next) {
49+
if (h1->val != h2->val) {
50+
return false;
51+
}
52+
}
53+
return true;
54+
}
55+
};

0 commit comments

Comments
 (0)
Please sign in to comment.