-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0143-reorder-list.c
61 lines (49 loc) · 1.2 KB
/
0143-reorder-list.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverse(struct ListNode* head) {
struct ListNode* prev = NULL;
struct ListNode* curr = head;
struct ListNode* next = curr->next;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
void merge(struct ListNode* l1, struct ListNode* l2) {
while (l1 != NULL) {
struct ListNode* p1 = l1->next;
struct ListNode* p2 = l2->next;
l1->next = l2;
if (p1 == NULL) {
break;
}
l2->next = p1;
l1 = p1;
l2 = p2;
}
}
void reorderList(struct ListNode* head){
if (head->next == NULL) {
return;
}
struct ListNode* prev = NULL;
struct ListNode* slow = head;
struct ListNode* fast = head;
while (fast != NULL && fast->next != NULL) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = NULL;
struct ListNode* l1 = head;
struct ListNode* l2 = reverse(slow);
merge(l1, l2);
}