Skip to content

Fix LinkedList removeAt() #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions src/_DataStructures_/LinkedList/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,30 +121,33 @@ class LinkedList {
return node;
}

removeAt(index) {
removeAt (index) {
if (!this.head) {
return null;
return null
}

if (index >= this.length()) {
if (index === 0) {
let returnNode=this.head;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this?

this.head=this.head.next;
this.size -= 1;
return returnNode;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return this.head from here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  if (!this.head) {
      this.head = node;
      this.tail = node;
      return node;
    }

If you do not make it null it will contain the full list

}
if (index >= this.size) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in linked list we don't keep size

return this.removeFromEnd();
}

let address = this.head;
let previous = address;
let count = index;

while (count) {
address = address.next;
while (count !== 1) {
previous = address;
address = address.next;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

better name

count -= 1;
}

const node = address;
previous.next = address.next.next;
previous.next = address.next;
this.size -= 1;
node.next = null;
return node;
return address;
}

length() {
Expand Down