Last active
August 10, 2018 18:09
-
-
Save thedineshj/3f6c0792e10dca7982469ed0cf8bc76c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
delete(value) { | |
/* | |
if the list is empty | |
*/ | |
if (this.head == null) { | |
console.log("The list is empty"); | |
} | |
/* | |
Traverse through list recursively | |
*/ | |
else { | |
let currentNode = this.head; | |
let previousNode = null; | |
while (currentNode != null) { | |
/* | |
if `data` of `currentnode` matches | |
with `value` | |
*/ | |
if (currentNode.data == value) { | |
break; | |
} | |
/* | |
if not,set `previousnode` to `currentnode` | |
so that if the `value` is found in the next iteration | |
we can use `previousnode` to remove the `node` | |
*/ | |
previousNode = currentNode; | |
currentNode = currentNode.next; | |
} | |
/* | |
if `value` is not in the list | |
*/ | |
if (currentNode == null) { | |
console.log(`${value} is not in the list`); | |
} | |
/* | |
if `value` is in the list | |
*/ | |
else { | |
/* | |
if it is the `head` of the list | |
then set `head` of the list to | |
`next` of `currentnode` | |
*/ | |
if (currentNode.data == this.head.data) { | |
this.head = currentNode.next; | |
} | |
/* | |
if not,point `next` of `previousnode` | |
to `next` of `currentnode` so that `currentnode` | |
will be removed from the list | |
*/ | |
else { | |
previousNode.next = currentNode.next; | |
} | |
/* | |
decrement length | |
*/ | |
this.length--; | |
console.log(`${value} is deleted from the list`); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment