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 9084503

Browse files
committed
fix: removeAt() work as an array and returns a Node
1 parent d9ab18c commit 9084503

File tree

1 file changed

+55
-26
lines changed
  • src/_DataStructures_/LinkedList

1 file changed

+55
-26
lines changed

‎src/_DataStructures_/LinkedList/index.js‎

Lines changed: 55 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -122,33 +122,38 @@ class LinkedList {
122122
}
123123

124124
removeAt(index) {
125-
if (!this.head) {
126-
return null;
127-
}
128-
if (index==1){
129-
this.head=this.head.next
130-
this.size -= 1;
131-
return
132-
}
133-
if (index >= this.size) {
134-
return this.removeFromEnd();
135-
136-
}
137-
138-
let address = this.head;
139-
let previous = address;
140-
let count = index;
141-
142-
while (count!=1) {
143-
previous = address;
144-
address = address.next;
145-
count -= 1;
146-
}
147-
148-
previous.next = address.next;
149-
console.log(address.next)
150-
this.size -= 1;
125+
if (!this.head) {
126+
return null;
127+
}
128+
if (index === 0) {
129+
const node = this.head;
130+
this.head = this.head.next;
131+
this.size -= 1;
132+
// set the next of the node null
133+
node.next = null;
134+
return node;
135+
}
136+
137+
if (index >= this.size - 1) {
138+
return this.removeFromEnd();
139+
}
140+
141+
let address = this.head;
142+
let previous = address;
143+
let count = index;
144+
145+
while (count >= 1) {
146+
previous = address;
147+
address = address.next;
148+
count -= 1;
151149
}
150+
const node = previous.next;
151+
previous.next = address.next;
152+
this.size -= 1;
153+
154+
node.next = null;
155+
return node;
156+
}
152157

153158
length() {
154159
return this.size;
@@ -159,6 +164,30 @@ class LinkedList {
159164
this.tail = this.head;
160165
this.size = 0;
161166
}
167+
168+
traverseList() {
169+
const arr = [];
170+
let node = this.head;
171+
while (node !== null) {
172+
arr.push(node.data);
173+
node = node.next;
174+
}
175+
return arr;
176+
}
162177
}
163178

179+
// const ll = new LinkedList();
180+
// ll.addAtBeginning(20);
181+
// ll.addAtBeginning(15);
182+
// ll.addAtBeginning(10);
183+
// ll.addAtBeginning(5);
184+
185+
// console.log(ll.traverseList());
186+
187+
// console.log(ll.removeAt(0));
188+
// console.log(ll.traverseList());
189+
190+
// console.log(ll.removeAt(1));
191+
// console.log(ll.traverseList());
192+
164193
module.exports = { LinkedList, Node };

0 commit comments

Comments
(0)

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