forked from imsushant12/GFG-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Given_a_linked_list_of_0s_1s_and_2s-sort_it.cpp
79 lines (67 loc) · 2.22 KB
/
Given_a_linked_list_of_0s_1s_and_2s-sort_it.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
/*
Problem Statement:
-----------------
Given a linked list of N nodes where nodes can contain values 0s, 1s, and 2s only. The task is to segregate 0s, 1s, and 2s linked list such that all zeros segregate
to head side, 2s at the end of the linked list, and 1s in the mid of 0s and 2s.
Example 1:
---------
Input:
N = 8
value[] = {1,2,2,1,2,0,2,2}
Output: 0 1 1 2 2 2 2 2
Explanation: All the 0s are segregated to the left end of the linked list, 2s to the right end of the list, and 1s in between.
Example 2:
---------
Input:
N = 4
value[] = {2,2,0,1}
Output: 0 1 2 2
Explanation: After arranging all the 0s,1s and 2s in the given format, the output will be 0 1 2 2.
Your Task: The task is to complete the function segregate() which segregates the nodes in the linked list as asked in the problem statement and
returns the head of the modified linked list. The printing is done automatically by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
*/
// Link --> https://practice.geeksforgeeks.org/problems/given-a-linked-list-of-0s-1s-and-2s-sort-it/1
// Code:
class Solution
{
public:
Node* segregate(Node *head)
{
Node* zeroHead = new Node(0);
Node* oneHead = new Node(0);
Node* twoHead = new Node(0);
Node* zero = zeroHead, *one = oneHead, *two = twoHead;
Node* cuurent = head;
while (cuurent)
{
if (cuurent->data == 0)
{
zero->next = cuurent;
zero = zero->next;
cuurent = cuurent->next;
}
else if (cuurent->data == 1)
{
one->next = cuurent;
one = one->next;
cuurent = cuurent->next;
}
else
{
two->next = cuurent;
two = two->next;
cuurent = cuurent->next;
}
}
zero->next = (oneHead->next) ? (oneHead->next) : (twoHead->next);
one->next = twoHead->next;
two->next = NULL;
head = zeroHead->next;
delete zeroHead;
delete oneHead;
delete twoHead;
return head;
}
};