Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 667d8c4

Browse files
author
Swastikyadav
committed
Add insertAt method in linkedList class
1 parent f68eb73 commit 667d8c4

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

‎18-linkedList.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,24 @@ class LinkedList {
138138

139139
prevNode.next = prevNode.next.next;
140140
}
141+
142+
// insertAt - Insert the given node at the given index.
143+
insertAt(data, idx) {
144+
if (!this.head) {
145+
this.head = new Node(data);
146+
return;
147+
}
148+
149+
if (idx === 0) {
150+
this.head = new Node(data, this.head);
151+
return;
152+
}
153+
154+
const prevNode = this.getAt(idx - 1) || this.getLast();
155+
const newNode = new Node(data, prevNode.next);
156+
157+
prevNode.next = newNode;
158+
}
141159
}
142160

143161
// -------------------------
@@ -165,4 +183,6 @@ console.log(list.getAt(1));
165183

166184
list.removeAt(1);
167185

186+
list.insertAt(50, 1);
187+
168188
console.log(list);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /