-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sort_a_linked_list_of_0s_1s_and_2s.cpp
116 lines (95 loc) · 2.34 KB
/
Sort_a_linked_list_of_0s_1s_and_2s.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
/* Link list Node */
struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = nullptr;
}
};
void printList(Node* node) {
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << "\n";
}
void freeList(struct Node* head) {
struct Node* temp;
while (head != NULL) {
temp = head;
head = head->next;
delete temp;
}
}
// } Driver Code Ends
/*
Node is defined as
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
*/
class Solution {
public:
// Function to sort a linked list of 0s, 1s and 2s.
Node* segregate(Node* head) {
int cnt_0 = 0;
int cnt_1 = 0;
int cnt_2 = 0;
Node* p = head;
while(p != NULL)
{
if(p->data == 0) cnt_0++;
else if(p->data == 1) cnt_1++;
else cnt_2++;
p = p->next;
}
p = head;
while(p != NULL)
{
while(cnt_0 > 0) p->data = 0, cnt_0--, p = p->next;
while(cnt_1 > 0) p->data = 1, cnt_1--, p = p->next;
while(cnt_2 > 0) p->data = 2, cnt_2--, p = p->next;
}
return head;
}
};
//{ Driver Code Starts.
// Driver program to test above functions
int main() {
int t, k;
cin >> t;
cin.ignore(); // Ignore the newline character after t
while (t--) {
string input;
getline(cin, input); // Read the entire line for the array elements
stringstream ss(input);
Node *head = nullptr, *tail = nullptr;
int x;
if (ss >> x) {
head = new Node(x);
tail = head;
while (ss >> x) {
tail->next = new Node(x);
tail = tail->next;
}
// Link the last node to the head if k is 1 to make it circular
if (k == 1) {
tail->next = head;
}
}
Solution ob;
Node* newHead = ob.segregate(head);
printList(newHead);
}
return 0;
}
// } Driver Code Ends