- Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathleetcode143-reorder-list_even_odd_analysis.cpp
72 lines (66 loc) · 1.6 KB
/
leetcode143-reorder-list_even_odd_analysis.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
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
#include<vector>
#include<algorithm>
usingnamespacestd;
/**
* Definition for singly-linked list.
*/
structListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
classSolution {
public:
voidreorderList(ListNode* head) {
auto fakeNode = newListNode(-1);
vector<ListNode*> arr = getNewArr(head);
fakeNode->next = arr[0];
for (int i = 0; i < arr.size() - 1; i++)
arr[i]->next = arr[i+1];
arr.back()->next = nullptr;
head = fakeNode->next;
}
vector<ListNode*> getNewArr(ListNode* head)
{
vector<ListNode*> oriArr;
vector<ListNode*> newArr;
auto p = head;
while (p)
{
oriArr.push_back(p);
p = p->next;
}
int count = oriArr.size();
for (int i = 0; i <= oriArr.size()/2 + 1; i++)
{
if (count >= 2)
{
newArr.push_back(oriArr[i]);
newArr.push_back(oriArr[oriArr.size() - 1 - i]);
count -= 2;
}
}
if (count == 1)
newArr.push_back(oriArr[oriArr.size()/2]);
return newArr;
}
};
// Test
intmain()
{
Solution sol;
ListNode *head = newListNode(1);
head->next = newListNode(2);
head->next->next = newListNode(3);
head->next->next->next = newListNode(4);
head->next->next->next->next = NULL;
sol.reorderList(head);
ListNode* p = head;
while (p != NULL)
{
cout << p->val << endl;
p = p->next;
}
return0;
}