-
Notifications
You must be signed in to change notification settings - Fork 1
/
143_Reordered_List.cpp
89 lines (83 loc) · 1.54 KB
/
143_Reordered_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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// Approch-1
void reorderList(ListNode *head)
{
ListNode *temp = head;
vector<int> res;
while (temp)
{
res.push_back(temp->val);
temp = temp->next;
}
if (res.size() <= 2)
return;
int n = res.size();
int i = 0, idx = 0;
vector<int> nodes(n);
while (idx < n)
{
nodes[idx] = res[i];
idx = idx + 2;
i++;
}
idx = 1, i = n - 1;
while (idx < n)
{
nodes[idx] = res[i];
i--;
idx += 2;
}
ListNode *order = head;
for (auto val : nodes)
{
order->val = val;
order = order->next;
}
}
// Approch-2
ListNode *middle(ListNode *head)
{
ListNode *slow = head;
ListNode *fast = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode *reverse(ListNode *head)
{
ListNode *prev = NULL;
ListNode *next = NULL;
while (head)
{
next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
void reorderList(ListNode *head)
{
ListNode *mid = middle(head);
ListNode *rev = reverse(mid->next);
mid->next = NULL;
while (head && rev)
{
ListNode *p = head->next;
ListNode *q = rev->next;
head->next = rev;
head->next->next = p;
head = p;
rev = q;
}
}