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 f68eb73

Browse files
author
Swastikyadav
committed
Add getAt and removeAt methods in linkedList class
1 parent e9a2a8a commit f68eb73

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎18-linkedList.js‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,39 @@ class LinkedList {
105105
this.head = new Node(data);
106106
}
107107
}
108+
109+
// getAt - Get node at a given index.
110+
getAt(idx) {
111+
const nodeArr = [];
112+
let listNode = this.head;
113+
114+
if (!listNode) return null;
115+
116+
while (listNode) {
117+
nodeArr.push(listNode);
118+
listNode = listNode.next;
119+
}
120+
121+
return nodeArr[idx];
122+
}
123+
124+
// removeAt - Remove a node at a given index.
125+
removeAt(idx) {
126+
if (!this.head) {
127+
return;
128+
}
129+
130+
if (idx === 0) {
131+
this.removeFirst();
132+
return;
133+
};
134+
135+
const prevNode = this.getAt(idx - 1);
136+
137+
if (!prevNode || !prevNode.next) return;
138+
139+
prevNode.next = prevNode.next.next;
140+
}
108141
}
109142

110143
// -------------------------
@@ -126,4 +159,10 @@ console.log(list);
126159

127160
list.insertLast(30);
128161

162+
console.log(list);
163+
164+
console.log(list.getAt(1));
165+
166+
list.removeAt(1);
167+
129168
console.log(list);

0 commit comments

Comments
(0)

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