-
Notifications
You must be signed in to change notification settings - Fork 119
/
234.c
115 lines (88 loc) · 1.88 KB
/
234.c
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
104
105
106
107
108
109
110
111
112
113
114
115
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct ListNode {
int val;
struct ListNode *next;
};
bool isPalindrome(struct ListNode* head) {
if (head == NULL) return true;
struct ListNode *p = head;
int len = 0;
while (p) {
len++;
p = p->next;
}
int half = len / 2;
/* get the middle node */
p = head;
while (half--) {
p = p->next;
}
/* skip middle if length is odd */
if (len % 2 == 1) {
p = p->next;
}
/* reverse the right half */
struct ListNode *prev = NULL, *next = NULL;
while (p) {
next = p->next;
p->next = prev;
prev = p;
p = next;
}
struct ListNode *q = prev;
p = head;
half = len / 2;
while (half--) {
if (p->val != q->val)
return false;
p = p->next;
q = q->next;
}
return true;
}
void printList(struct ListNode* head) {
if (head == NULL) return;
while (head) {
printf("%d->", head->val);
head = head->next;
}
printf("N\n");
}
int main() {
struct ListNode *l1 = (struct ListNode *)calloc(4, sizeof(struct ListNode));
struct ListNode *l2 = (struct ListNode *)calloc(5, sizeof(struct ListNode));
struct ListNode *p = l1;
p->val = 1;
p->next = l1 + 1;
p = p->next;
p->val = 2;
p->next = l1 + 2;
p = p->next;
p->val = 2;
p->next = l1 + 3;
p = p->next;
p->val = 1;
p->next = NULL;
p = l2;
p->val = 1;
p->next = l2 + 1;
p = p->next;
p->val = 2;
p->next = l2 + 2;
p = p->next;
p->val = 3;
p->next = l2 + 3;
p = p->next;
p->val = 2;
p->next = l2 + 4;
p = p->next;
p->val = 1;
p->next = NULL;
printList(l1);
printf("%d\n", isPalindrome(l1));
printList(l2);
printf("%d\n", isPalindrome(l2));
return 0;
}