-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18-DLL Insertion.js
More file actions
94 lines (73 loc) · 1.66 KB
/
18-DLL Insertion.js
File metadata and controls
94 lines (73 loc) · 1.66 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
class Node {
constructor(data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
}
insertAtStart(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
return;
}
newNode.next = this.head;
this.head.prev = newNode;
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;
newNode.prev = current;
}
insertAtPosition(data, index) {
if (index == 0) {
this.insertAtStart(data);
return;
}
const newNode = new Node(data);
let current = this.head;
let i = 0;
while (current && i < index - 1) {
current = current.next;
i++;
}
newNode.next = current.next;
if (current.next) {
current.next.prev = newNode;
}
current.next = newNode;
newNode.prev = current;
}
printList() {
let current = this.head;
let result = "null ← ";
while (current) {
result += current.data + " ↔ ";
current = current.next;
}
result += "null";
console.log(result);
}
}
const list = new DoublyLinkedList();
list.insertAtStart(30);
list.insertAtStart(20);
list.insertAtStart(10);
list.printList(); // null ← 10 ↔ 20 ↔ 30 ↔ null`
list.insertAtEnd(40);
list.printList(); // null ← 10 ↔ 20 ↔ 30 ↔ 40 ↔ null
list.insertAtPosition(25, 2);
list.printList(); // null ← 10 ↔ 20 ↔ 25 ↔ 30 ↔ 40 ↔ null