Skip to content

Commit 67fc0bd

Browse files
authored
Create insert-into-a-cyclic-sorted-list.cpp
1 parent 488e46e commit 67fc0bd

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
/*
5+
// Definition for a Node.
6+
class Node {
7+
public:
8+
int val;
9+
Node* next;
10+
11+
Node() {}
12+
13+
Node(int _val, Node* _next) {
14+
val = _val;
15+
next = _next;
16+
}
17+
};
18+
*/
19+
class Solution {
20+
public:
21+
Node* insert(Node* head, int insertVal) {
22+
if (head == nullptr) {
23+
auto node = new Node(insertVal, nullptr);
24+
node->next = node;
25+
return node;
26+
}
27+
auto curr = head;
28+
while (true) {
29+
if (curr->val < curr->next->val) {
30+
if (curr->val <= insertVal &&
31+
insertVal <= curr->next->val) {
32+
insertAfter(curr, insertVal);
33+
break;
34+
}
35+
} else if (curr->val > curr->next->val) {
36+
if (curr->val <= insertVal ||
37+
insertVal <= curr->next->val) {
38+
insertAfter(curr, insertVal);
39+
break;
40+
}
41+
} else {
42+
if (curr->next == head) {
43+
insertAfter(curr, insertVal);
44+
break;
45+
}
46+
}
47+
curr = curr->next;
48+
}
49+
return head;
50+
}
51+
52+
private:
53+
void insertAfter(Node *node, int val) {
54+
node->next = new Node(val, node->next);
55+
}
56+
};

0 commit comments

Comments
 (0)