-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
51 lines (48 loc) · 1.21 KB
/
index.ts
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
import { ListNode as Node } from "../reverse-linked-list/ListNode.ts";
/**
* Definition for node.
* class Node {
* val: number
* next: Node | null
* constructor(val?: number, next?: Node) {
* this.val = (val===undefined ? 0 : val);
* this.next = (next===undefined ? null : next);
* }
* }
*/
export default function insert(
head: Node | null,
insertVal: number,
): Node | null {
if (!head) {
const node = new Node(insertVal);
node.next = node;
return node;
}
const node = new Node(insertVal);
let cur = head;
while (cur.next !== head) {
const nextval = cur.next?.val;
if (typeof nextval == "undefined") {
throw Error("none next node");
}
if (cur.val <= insertVal && nextval >= insertVal) {
break;
}
if (cur.val > nextval) {
if (nextval >= insertVal) {
break;
} else if (cur.val <= insertVal) {
break;
}
}
if (cur.next) {
cur = cur.next;
} else {
throw Error("none next node");
}
}
node.next = cur.next;
cur.next = node;
return head;
}