-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-029-insertNode.js
79 lines (59 loc) · 1.4 KB
/
structy-029-insertNode.js
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// https://structy.net/problems/premium/insert-node
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
// p: head of ll & str & num
// r: head of ll
// a -------> b -------> c -------> d
// p c
// p.n v
//
// recursion
const insertNode = (head, value, index, v = new Node(value)) => {
if (index === 0) {
v.next = head;
return v;
}
head.next = insertNode(head.next, value, index - 1, v);
return head;
};
// // iteration
// const insertNode = (head, value, index) => {
// let v = new Node(value);
// if (index === 0) {
// v.next = head;
// return v;
// }
// let current = head;
// let prev = null;
// for (let i = 0; i <= index; i++) {
// if (i === index) {
// prev.next = v;
// v.next = current;
// break;
// }
// prev = current;
// current = current.next;
// }
// return head;
// };
const a = new Node("a");
const b = new Node("b");
const c = new Node("c");
const d = new Node("d");
a.next = b;
b.next = c;
c.next = d;
// a -> b -> c -> d
console.log(insertNode(a, "x", 2));
// deletenode
// const delNode = (head, val) => {
// if (val === head.val) return head.next;
// head.next = delNode(head.next, val);
// return head;
// };
// console.log(delNode(a, "c"));
// a -> b -> x -> c -> d