Skip to content

Commit 8d045e1

Browse files
committed
feat: add ts solution to lcof2 problem: No.029
剑指 Offer II 029. 排序的循环链表
1 parent 10ceaba commit 8d045e1

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

lcof2/剑指 Offer II 029. 排序的循环链表/README.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,52 @@ public:
214214
};
215215
```
216216
217+
### **TypeScript**
218+
219+
```ts
220+
/**
221+
* Definition for node.
222+
* class Node {
223+
* val: number
224+
* next: Node | null
225+
* constructor(val?: number, next?: Node) {
226+
* this.val = (val===undefined ? 0 : val);
227+
* this.next = (next===undefined ? null : next);
228+
* }
229+
* }
230+
*/
231+
232+
function insert(head: Node | null, insertVal: number): Node | null {
233+
const newNode = new Node(insertVal);
234+
if (head == null) {
235+
newNode.next = newNode;
236+
return newNode;
237+
}
238+
const dummy = new Node(0, head);
239+
let cur = dummy.next;
240+
while (cur.next != dummy.next) {
241+
const val = cur.val;
242+
const nextVal = cur.next.val;
243+
if (val > nextVal) {
244+
if (
245+
(insertVal >= val && insertVal >= nextVal) ||
246+
(insertVal <= val && insertVal <= nextVal)
247+
) {
248+
break;
249+
}
250+
} else {
251+
if (insertVal >= val && insertVal <= nextVal) {
252+
break;
253+
}
254+
}
255+
cur = cur.next;
256+
}
257+
newNode.next = cur.next;
258+
cur.next = newNode;
259+
return dummy.next;
260+
}
261+
```
262+
217263
### **...**
218264

219265
```
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for node.
3+
* class Node {
4+
* val: number
5+
* next: Node | null
6+
* constructor(val?: number, next?: Node) {
7+
* this.val = (val===undefined ? 0 : val);
8+
* this.next = (next===undefined ? null : next);
9+
* }
10+
* }
11+
*/
12+
13+
function insert(head: Node | null, insertVal: number): Node | null {
14+
const newNode = new Node(insertVal);
15+
if (head == null) {
16+
newNode.next = newNode;
17+
return newNode;
18+
}
19+
const dummy = new Node(0, head);
20+
let cur = dummy.next;
21+
while (cur.next != dummy.next) {
22+
const val = cur.val;
23+
const nextVal = cur.next.val;
24+
if (val > nextVal) {
25+
if (
26+
(insertVal >= val && insertVal >= nextVal) ||
27+
(insertVal <= val && insertVal <= nextVal)
28+
) {
29+
break;
30+
}
31+
} else {
32+
if (insertVal >= val && insertVal <= nextVal) {
33+
break;
34+
}
35+
}
36+
cur = cur.next;
37+
}
38+
newNode.next = cur.next;
39+
cur.next = newNode;
40+
return dummy.next;
41+
}

0 commit comments

Comments
 (0)