forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
143.c
95 lines (78 loc) · 1.83 KB
/
143.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
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *Helper(struct ListNode **forward, struct ListNode *node) {
if (node == NULL || node->next == NULL) return node;
struct ListNode *tail = Helper(forward, node->next);
if (*forward == tail || (*forward)->next == tail) return tail;
struct ListNode *t = (*forward)->next;
(*forward)->next = tail;
*forward = t;
tail->next = t;
return node;
}
void reorderList(struct ListNode* head) {
if (head == NULL) return;
struct ListNode *p = head;
struct ListNode *mid = Helper(&p, head);
mid->next = NULL;
}
struct ListNode *createNode(int new_data) {
struct ListNode *new_node = (struct ListNode *)malloc(sizeof(struct ListNode));
new_node->val = new_data;
new_node->next = NULL;
return new_node;
}
int main(){
/* test 1 */
struct ListNode *l1 = createNode(1);
struct ListNode *p = l1;
int i;
for (i = 2; i <= 5; i++) {
p->next = createNode(i);
p = p->next;
}
p->next = NULL;
printf("List 1: ");
p = l1;
while (p) {
printf("%d->", p->val);
p = p->next;
}
printf("NIL\n");
reorderList(l1);
printf("Reorder: ");
p = l1;
while (p) {
printf("%d->", p->val);
p = p->next;
}
printf("NIL\n");
/* test 2 */
struct ListNode *l2 = createNode(1);
p = l2;
for (i = 2; i <= 6; i++) {
p->next = createNode(i);
p = p->next;
}
p->next = NULL;
printf("List 2: ");
p = l2;
while (p) {
printf("%d->", p->val);
p = p->next;
}
printf("NIL\n");
reorderList(l2);
printf("Reorder: ");
p = l2;
while (p) {
printf("%d->", p->val);
p = p->next;
}
printf("NIL\n");
return 0;
}