Skip to content

Commit 9479f76

Browse files
committed
"Palindrome Linked List"
1 parent 09adeb0 commit 9479f76

File tree

2 files changed

+116
-1
lines changed

2 files changed

+116
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ You can build all the files using `make` (Use MinGW GCC and GNU Make on Windows)
2424

2525
| | Problem | Solution |
2626
| --- | ------------------------------------------------------------ | ------------------ |
27-
| 234 | [Palindrome Linked List] | |
27+
| 234 | [Palindrome Linked List] | [C](src/234.c) |
2828
| 233 | [Number of Digit One] | |
2929
| 232 | [Implement Queue using Stacks] | [C](src/232.c) |
3030
| 231 | [Power of Two] | [C](src/231.c) |

Diff for: src/234.c

+115
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <stdbool.h>
4+
5+
struct ListNode {
6+
int val;
7+
struct ListNode *next;
8+
};
9+
10+
bool isPalindrome(struct ListNode* head) {
11+
if (head == NULL) return true;
12+
13+
struct ListNode *p = head;
14+
int len = 0;
15+
while (p) {
16+
len++;
17+
p = p->next;
18+
}
19+
20+
int half = len / 2;
21+
22+
/* get the middle node */
23+
p = head;
24+
while (half--) {
25+
p = p->next;
26+
}
27+
28+
/* skip middle if length is odd */
29+
if (len % 2 == 1) {
30+
p = p->next;
31+
}
32+
33+
/* reverse the right half */
34+
struct ListNode *prev = NULL, *next = NULL;
35+
while (p) {
36+
next = p->next;
37+
p->next = prev;
38+
prev = p;
39+
p = next;
40+
}
41+
42+
struct ListNode *q = prev;
43+
p = head;
44+
half = len / 2;
45+
46+
while (half--) {
47+
if (p->val != q->val)
48+
return false;
49+
p = p->next;
50+
q = q->next;
51+
}
52+
53+
return true;
54+
}
55+
56+
void printList(struct ListNode* head) {
57+
if (head == NULL) return;
58+
59+
while (head) {
60+
printf("%d->", head->val);
61+
head = head->next;
62+
}
63+
printf("N\n");
64+
}
65+
66+
int main() {
67+
68+
struct ListNode *l1 = (struct ListNode *)calloc(4, sizeof(struct ListNode));
69+
struct ListNode *l2 = (struct ListNode *)calloc(5, sizeof(struct ListNode));
70+
71+
struct ListNode *p = l1;
72+
73+
p->val = 1;
74+
p->next = l1 + 1;
75+
p = p->next;
76+
77+
p->val = 2;
78+
p->next = l1 + 2;
79+
p = p->next;
80+
81+
p->val = 2;
82+
p->next = l1 + 3;
83+
p = p->next;
84+
85+
p->val = 1;
86+
p->next = NULL;
87+
88+
p = l2;
89+
p->val = 1;
90+
p->next = l2 + 1;
91+
p = p->next;
92+
93+
p->val = 2;
94+
p->next = l2 + 2;
95+
p = p->next;
96+
97+
p->val = 3;
98+
p->next = l2 + 3;
99+
p = p->next;
100+
101+
p->val = 2;
102+
p->next = l2 + 4;
103+
p = p->next;
104+
105+
p->val = 1;
106+
p->next = NULL;
107+
108+
printList(l1);
109+
printf("%d\n", isPalindrome(l1));
110+
111+
printList(l2);
112+
printf("%d\n", isPalindrome(l2));
113+
114+
return 0;
115+
}

0 commit comments

Comments
 (0)