Skip to content

Commit d9ab18c

Browse files
authored
Fix LinkedList removeAt()
1.added base case for removeAt(1) 2.switched assigment on line knaxus#138 where previous and current where pointing to the same node
1 parent 9e01c43 commit d9ab18c

File tree

1 file changed

+26
-23
lines changed

1 file changed

+26
-23
lines changed

src/_DataStructures_/LinkedList/index.js

+26-23
Original file line numberDiff line numberDiff line change
@@ -122,31 +122,34 @@ class LinkedList {
122122
}
123123

124124
removeAt(index) {
125-
if (!this.head) {
126-
return null;
127-
}
128-
129-
if (index >= this.length()) {
130-
return this.removeFromEnd();
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;
131151
}
132152

133-
let address = this.head;
134-
let previous = address;
135-
let count = index;
136-
137-
while (count) {
138-
address = address.next;
139-
previous = address;
140-
count -= 1;
141-
}
142-
143-
const node = address;
144-
previous.next = address.next.next;
145-
this.size -= 1;
146-
node.next = null;
147-
return node;
148-
}
149-
150153
length() {
151154
return this.size;
152155
}

0 commit comments

Comments
 (0)