-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreorder_list.cpp
More file actions
69 lines (57 loc) · 1.57 KB
/
reorder_list.cpp
File metadata and controls
69 lines (57 loc) · 1.57 KB
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
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: void
*/
void reorderList(ListNode *head) {
// write your code here
if (head == NULL || head->next == NULL || head->next->next == NULL) {
return;
}
ListNode *preMid = findPreMid(head);
ListNode *right_part = preMid->next;
preMid->next = NULL;
ListNode *left_part = head;
right_part = reverse(right_part);
while (left_part != NULL && right_part != NULL) {
ListNode* temp = left_part->next;
left_part->next = right_part;
ListNode* temp2 = right_part->next;
right_part->next = temp;
left_part = temp;
right_part = temp2;
}
}
ListNode* reverse(ListNode *head) {
ListNode dummy(0);
while (head != NULL) {
ListNode* temp = head->next;
head->next = dummy.next;
dummy.next = head;
head = temp;
}
return dummy.next;
}
ListNode* findPreMid(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head->next;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};