-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay_62.cpp
49 lines (41 loc) · 1.26 KB
/
Day_62.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
/*
DAY 62 : Sorted insert for circular linked list.
https://www.geeksforgeeks.org/sorted-insert-for-circular-linked-list/
QUESTION : Given a sorted circular linked list, the task is to insert a new node in this circular
list so that it remains a sorted circular linked list.
Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)
Constraints:
0 <= N <= 10^5
*/
class Solution
{
public:
Node *sortedInsert(Node* head, int data)
{
//Your code here
Node* prev = NULL;
Node* current = head;
Node* newNode = new Node(data);
if (head == NULL) {
newNode->next = NULL;
head = newNode;
}
else if (current->data >= newNode->data) {
while (current->next != head) {
current = current->next;
}
current->next = newNode;
newNode->next = head;
head = newNode;
}
else {
while (current->next != head && current->next->data < newNode->data) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
return head;
}
}
};