[LeetCode] Insert into a Sorted Circular Linked List

708. Insert into a Sorted Circular Linked List

Given a node from a Circular Linked List which is sorted in ascending order, write a function to insert a value insertVal into the list such that it remains a sorted circular 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 circular list.

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

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

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

Node() {}

Node(int _val) {
val = _val;
next = NULL;
}

Node(int _val, Node* _next) {
val = _val;
next = _next;
}
};
*/

class Solution {
private:
Node* findNode(Node* head, int value) {
Node* cur = head;
if(head->val != value) {
while(cur->next != head && !(
(cur->next->val >= value && cur->val <= value) ||
(cur->next->val >= value && cur->val > value && cur->val > cur->next->val) ||
(cur->next->val <= value && cur->val < value && cur->val > cur->next->val))) {
cur = cur->next;
}
}
return cur;
}
public:
Node* insert(Node* head, int insertVal) {
if(head == nullptr) {
head = new Node(insertVal);
head->next = head;
} else {
Node *node = findNode(head, insertVal);
node->next = new Node(insertVal, node->next);
}
return head;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/13/PS/LeetCode/insert-into-a-sorted-circular-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.