Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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`);
- }
- }
- }
Add Comment
Please, Sign In to add comment