-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11-LINKED LIST INSERTION.js
More file actions
86 lines (68 loc) · 1.47 KB
/
Copy path11-LINKED LIST INSERTION.js
File metadata and controls
86 lines (68 loc) · 1.47 KB
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
80
81
82
83
84
85
86
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
printLL() {
let current = this.head;
while (current !== null) {
console.log(current.data);
current = current.next;
}
}
insertAtStart(data) {
const newNode = new Node(data);
newNode.next = this.head;
this.head = newNode;
}
insertAtEnd(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
insertAtPostion(index, data) {
const newNode = new Node(data);
if (index === 0) {
newNode.next = this.head;
this.head = newNode;
return;
}
let current = this.head;
let count = 0;
while (current !== null && count < index - 1) {
current = current.next;
count++;
}
if (current === null) {
console.log("Postion out of range");
return;
}
newNode.next = current.next;
current.next = newNode;
}
}
let list = new LinkedList();
list.head = new Node(10);
list.head.next = new Node(20);
list.head.next.next = new Node(30);
list.insertAtStart(0);
list.insertAtStart(-10);
list.insertAtStart(-20);
list.insertAtEnd(40);
list.insertAtEnd(50);
list.insertAtPostion(0, -90);
list.insertAtPostion(1, -100);
list.insertAtPostion(1, 5);
list.printLL();