Skip to content

Commit 9807459

Browse files
committed
"Reorder List"
1 parent d2ad4b7 commit 9807459

File tree

2 files changed

+96
-1
lines changed

2 files changed

+96
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
155155
| 146 | [LRU Cache] | [C](src/146.c) |
156156
| 145 | [Binary Tree Postorder Traversal] | [C](src/145.c) |
157157
| 144 | [Binary Tree Preorder Traversal] | [C++](src/144.cpp) |
158-
| 143 | [Reorder List] | |
158+
| 143 | [Reorder List] | [C](src/143.c) |
159159
| 142 | [Linked List Cycle II] | [C](src/142.c) |
160160
| 141 | [Linked List Cycle] | [C](src/141.c) |
161161
| 140 | [Word Break II] | |

src/143.c

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct ListNode {
5+
int val;
6+
struct ListNode *next;
7+
};
8+
9+
struct ListNode *Helper(struct ListNode **forward, struct ListNode *node) {
10+
if (node == NULL || node->next == NULL) return node;
11+
12+
struct ListNode *tail = Helper(forward, node->next);
13+
14+
if (*forward == tail || (*forward)->next == tail) return tail;
15+
16+
struct ListNode *t = (*forward)->next;
17+
(*forward)->next = tail;
18+
*forward = t;
19+
tail->next = t;
20+
21+
return node;
22+
}
23+
24+
void reorderList(struct ListNode* head) {
25+
if (head == NULL) return;
26+
struct ListNode *p = head;
27+
struct ListNode *mid = Helper(&p, head);
28+
mid->next = NULL;
29+
}
30+
31+
struct ListNode *createNode(int new_data) {
32+
struct ListNode *new_node = (struct ListNode *)malloc(sizeof(struct ListNode));
33+
new_node->val = new_data;
34+
new_node->next = NULL;
35+
return new_node;
36+
}
37+
38+
int main(){
39+
/* test 1 */
40+
struct ListNode *l1 = createNode(1);
41+
struct ListNode *p = l1;
42+
int i;
43+
for (i = 2; i <= 5; i++) {
44+
p->next = createNode(i);
45+
p = p->next;
46+
}
47+
p->next = NULL;
48+
49+
printf("List 1: ");
50+
p = l1;
51+
while (p) {
52+
printf("%d->", p->val);
53+
p = p->next;
54+
}
55+
printf("NIL\n");
56+
57+
reorderList(l1);
58+
59+
printf("Reorder: ");
60+
p = l1;
61+
while (p) {
62+
printf("%d->", p->val);
63+
p = p->next;
64+
}
65+
printf("NIL\n");
66+
67+
/* test 2 */
68+
struct ListNode *l2 = createNode(1);
69+
p = l2;
70+
for (i = 2; i <= 6; i++) {
71+
p->next = createNode(i);
72+
p = p->next;
73+
}
74+
p->next = NULL;
75+
76+
printf("List 2: ");
77+
p = l2;
78+
while (p) {
79+
printf("%d->", p->val);
80+
p = p->next;
81+
}
82+
printf("NIL\n");
83+
84+
reorderList(l2);
85+
86+
printf("Reorder: ");
87+
p = l2;
88+
while (p) {
89+
printf("%d->", p->val);
90+
p = p->next;
91+
}
92+
printf("NIL\n");
93+
94+
return 0;
95+
}

0 commit comments

Comments
 (0)