-
Notifications
You must be signed in to change notification settings - Fork 0
/
partition_linked_list.cc
98 lines (74 loc) · 1.92 KB
/
partition_linked_list.cc
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
90
91
92
93
94
95
96
97
98
/**
* 2.4 Partition linked lists from "Cracking coding interview"
*/
#include <iostream>
using namespace std;
struct Node {
int val;
Node* next = nullptr;
Node (int val_): val{val_} {}
};
#define SIMPLE
#ifdef SIMPLE
Node* partition(Node* node, int value) {
Node *head = node, *tail = node;
while (node) {
Node *next = node->next;
if (node->val < value) {
node->next = head;
head = node;
} else {
tail->next = node;
tail = node;
}
node = next;
}
tail->next = nullptr;
return head;
}
#else
Node* partition(Node* node, int value) {
Node *leftHead = nullptr, *rightHead = nullptr;
Node *left = nullptr, *right = nullptr;
while (node) {
if (node->val < value) {
// add to left side
if (left) left->next = node;
else leftHead = node;
left = node;
} else {
// add to right side
if (right) right->next = node;
else rightHead = node;
right = node;
}
node = node->next;
}
if (right) right->next = nullptr;
if (left) left->next = rightHead;
else leftHead = rightHead;
return leftHead;
}
#endif
void display(Node* node, const string message) {
cout << message << endl;
while (node) {
cout << node->val;
if (node->next) cout << " -> ";
node = node->next;
}
cout << endl;
}
int main() {
Node* head = new Node(3);
Node* node = head;
node->next = new Node(5); node = node->next;
node->next = new Node(8); node = node->next;
node->next = new Node(5); node = node->next;
node->next = new Node(10); node = node->next;
node->next = new Node(2); node = node->next;
node->next = new Node(1); node = node->next;
display(head, "Initial list:");
head = partition(head, 5);
display(head, "After:");
}