-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorderList.c
78 lines (64 loc) · 1.5 KB
/
reorderList.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode * reverseList(struct ListNode* head)
{
if (!head || !head->next) return head;
struct ListNode * prev = NULL;
struct ListNode * cur = head;
struct ListNode * next = head->next;
while (next)
{
cur->next = prev;
prev = cur;
cur = next;
next = next->next;
}
cur->next = prev;
return cur;
}
struct ListNode * mergeLists(struct ListNode * listA, struct ListNode * listB)
{
if (!listA) return listB;
if (!listB) return listA;
struct ListNode * i, * j, *temp;
i = listA;
j = listB;
struct ListNode newHead;
temp = &newHead;
while (i && j)
{
temp->next = i;
i = i->next;
temp = temp->next;
temp->next = j;
j = j->next;
temp = temp->next;
}
if (!i) temp->next = j;
else if (!j) temp->next = i;
return newHead.next;
}
void reorderList(struct ListNode* head) {
if (!head || !head->next) return;
struct ListNode * fast = head;
struct ListNode * slow = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
fast = head;
while (fast->next != slow)
{
fast = fast->next;
}
fast->next = reverseList(slow);
slow = fast->next;
fast->next = NULL;
head = mergeLists(head, slow);
}