Skip to content
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

fix: edit remove function of singly linked list #6067

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,23 +57,30 @@ function LinkedList() {
this.remove = function(element) {
var currentNode = head;
var previousNode;


// Check if head exist
if(!currentNode) console.log("list does not exist.");
Copy link
Contributor

Choose a reason for hiding this comment

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

i think it'd not be useful to just log, you need to handle it. you can simple use if-else block to not proceed next if the node isn't exist.

Copy link
Author

@damla damla Sep 8, 2021

Choose a reason for hiding this comment

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

Thanks for mentioning! I forgot to add return in there. Will fix it 😊


//Check if the head node is the element to remove
if (currentNode.element === element) {
head = currentNode.next;
length--;
} else {
//Check which node is the node to remove
while (currentNode.element !== element) {
while (currentNode.element !== element && currentNode.next) {
previousNode = currentNode;
currentNode = currentNode.next;
}

//Removing the currentNode
if(currentNode.element === element) {
//Removing the currentNode if the data is found after search
previousNode.next = currentNode.next;
length--;
}
else {
// if the node could not found, log it
console.log("element not found");
}
}

//Decrementing the length
length--;
};

//Return if the list is empty
Expand Down