-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartition_list.cpp
More file actions
54 lines (47 loc) · 842 Bytes
/
Copy pathpartition_list.cpp
File metadata and controls
54 lines (47 loc) · 842 Bytes
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
#include <stdio.h>
class Node {
Node *next;
int data;
public:
Node(int mydata, Node *nextNode) : data(mydata), next(nextNode) {}
~Node() {
if(next)
delete next;
}
void print() {
printf("%d\t", data);
if(next)
next->print();
}
Node *partition(int val) {
Node *part1 = NULL, *part2 = NULL;
Node *it = this;
while(it) {
Node *itNext = it->next;
if(it->data < val) {
it->next = part1;
part1 = it;
} else {
it->next = part2;
part2 = it;
}
it = itNext;
}
if(!part1)
return part2;
it = part1;
while(it->next)
it = it->next;
it->next = part2;
return part1;
}
};
int main() {
Node *head = new Node(1, new Node(2, new Node(3, new Node(1, new Node(4, NULL)))));
head->print();
printf("\n");
head = head->partition(2);
head->print();
printf("\n");
delete head;
}