-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
insert-into-a-sorted-circular-linked-list.cpp
56 lines (52 loc) · 1.29 KB
/
insert-into-a-sorted-circular-linked-list.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
// Time: O(n)
// Space: O(1)
/*
// 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) {
if (head == nullptr) {
auto node = new Node(insertVal, nullptr);
node->next = node;
return node;
}
auto curr = head;
while (true) {
if (curr->val < curr->next->val) {
if (curr->val <= insertVal &&
insertVal <= curr->next->val) {
insertAfter(curr, insertVal);
break;
}
} else if (curr->val > curr->next->val) {
if (curr->val <= insertVal ||
insertVal <= curr->next->val) {
insertAfter(curr, insertVal);
break;
}
} else {
if (curr->next == head) {
insertAfter(curr, insertVal);
break;
}
}
curr = curr->next;
}
return head;
}
private:
void insertAfter(Node *node, int val) {
node->next = new Node(val, node->next);
}
};