-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12-LINKED LIST DELETION.js
More file actions
97 lines (74 loc) · 1.53 KB
/
Copy path12-LINKED LIST DELETION.js
File metadata and controls
97 lines (74 loc) · 1.53 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
87
88
89
90
91
92
93
94
95
96
97
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
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;
}
printLL() {
let current = this.head;
while (current !== null) {
console.log(current.data);
current = current.next;
}
}
deleteFromStart() {
if (!this.head) return;
this.head = this.head.next;
}
deleteFromEnd() {
if (!this.head) return;
if (!this.head.next) {
this.head = null;
return;
}
let current = this.head;
while (current.next.next) {
current = current.next;
}
current.next = null;
}
deleteFromPosition(index) {
if (!this.head) return;
if (index === 0) {
this.head = this.head.next;
return;
}
let current = this.head;
let count = 0;
while (current.next !== null && count < index - 1) {
current = current.next;
count++;
}
if (current.next === null) {
console.log("Postion out of range");
return;
}
current.next = current.next.next;
}
}
const list = new LinkedList();
list.insertAtEnd(10);
list.insertAtEnd(20);
list.insertAtEnd(30);
list.deleteFromStart();
list.deleteFromEnd();
list.insertAtEnd(40);
list.insertAtEnd(50);
list.deleteFromPosition(1);
list.printLL();