Fork me on GitHub

Insert into a Cyclic Sorted List

Description

Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be a reference to any single node in the list, and may not be necessarily the smallest value in the cyclic list.

If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the cyclic list should remain sorted.

If the list is empty (i.e., given node is null), you should create a new single cyclic list and return the reference to that single node. Otherwise, you should return the original given node.

Solution

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
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;

Node() {}

Node(int _val, Node* _next) {
val = _val;
next = _next;
}
};
*/
class Solution {
public:
Node* insert(Node* head, int insertVal) {
Node* inserted = new Node(insertVal, NULL);
if (head == NULL) return inserted;

Node* cur = head;

if(insertVal < cur->val) {
while(cur->next != head &&
cur->next->val >= cur->val && cur->val > insertVal) cur = cur->next;
while(cur->next->val < insertVal) cur = cur->next;
}else if(insertVal > cur->val){
while(cur->next != head && cur->val <= cur->next->val
&& cur->next->val < insertVal) cur = cur->next;
}

inserted->next = cur->next;
cur->next = inserted;
return head;
}
};