-
Notifications
You must be signed in to change notification settings - Fork 0
/
143Reorder_list.cpp
58 lines (54 loc) · 1.47 KB
/
143Reorder_list.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
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
void reorderList(ListNode* head) {
if(head->next != NULL){
ListNode* cur = head;
int total = 0;
while(cur->next != NULL){
total++;
cur = cur->next;
}
total++;
int count = 0;
if(total%2 == 1) count = -1;
cur = head;
ListNode* head2;
while(count != total/2-1){
count++;
cur = cur->next;
}
head2 = cur->next;
cur->next = NULL;
ListNode* prev = head2;
ListNode* Next = head2->next;
ListNode* cur2 = head2;
while(Next != NULL){
cur2 = Next;
Next = Next->next;
cur2->next = prev;
prev = cur2;
}
head2->next = NULL;
head2 = cur2;
cur = head;
count = 0;
while(count != total/2){
count++;
ListNode* temp = cur2->next;
cur2->next = cur->next;
cur->next = cur2;
cur = cur->next->next;
cur2 = temp;
}
}
}
};