forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.cpp
61 lines (59 loc) · 1.36 KB
/
solution.cpp
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;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
void reverseList(ListNode *&head)
{
ListNode *h = new ListNode(0);
ListNode *tmp;
while (head != NULL)
{
tmp = head->next;
head->next = h->next;
h->next = head;
head = tmp;
}
head = h->next;
}
void twistList(ListNode *&l1, ListNode *&l2)
{
ListNode *p1, *p2, *tmp;
p1 = l1; p2 = l2;
while (p1 != NULL && p2 != NULL) {
tmp = p2->next;
p2->next = p1->next;
p1->next = p2;
p1 = p1->next->next;
p2 = tmp;
}
}
void reorderList(ListNode *head)
{
if (head == NULL || head->next == NULL || head->next->next == NULL)
{
return;
}
ListNode *slow, *fast;
slow = head; fast = head;
while (fast != NULL && fast->next != NULL)
{
slow = slow->next;
if (fast->next->next == NULL)
{
break;
}
fast = fast->next->next;
}
ListNode *l2 = slow->next;
slow->next = NULL;
reverseList(l2);
twistList(head, l2);
}
};