-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question32.cpp
113 lines (89 loc) · 1.88 KB
/
Question32.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
32 -> Sort a linked list of 0s, 1s and 2s by changing links
Solution :
//{ 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 = NULL;
}
};
struct Node *start = NULL;
// } 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) {
Node* curr = head;
vector<int> arr;
while(curr){
arr.push_back(curr->data);
curr = curr->next;
}
sort(arr.begin(), arr.end());
Node* temp = head;
for(int i=0;i<arr.size();i++){
temp->data = arr[i];
temp = temp->next;
}
return head;
}
};
//{ Driver Code Starts.
// Function to sort a linked list of 0s, 1s and 2s
void printList(struct Node *Node) {
while (Node != NULL) {
printf("%d ", Node->data);
Node = Node->next;
}
printf("\n");
}
/* Drier program to test above function*/
void insert(int n1) {
int n, value, i;
// scanf("%d",&n);
n = n1;
struct Node *temp;
for (i = 0; i < n; i++) {
scanf("%d", &value);
if (i == 0) {
start = new Node(value);
temp = start;
continue;
} else {
temp->next = new Node(value);
temp = temp->next;
temp->next = NULL;
}
}
}
int main() {
int n;
int t;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
insert(n);
Solution ob;
struct Node *newHead = ob.segregate(start);
printList(newHead);
}
return 0;
}
// } Driver Code Ends