File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments