Guest User

Untitled

a guest
Aug 10th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. delete(value) {
  2. /*
  3. if the list is empty
  4. */
  5. if (this.head == null) {
  6. console.log("The list is empty");
  7. }
  8. /*
  9. Traverse through list recursively
  10. */
  11. else {
  12. let currentNode = this.head;
  13. let previousNode = null;
  14. while (currentNode != null) {
  15. /*
  16. if `data` of `currentnode` matches
  17. with `value`
  18. */
  19. if (currentNode.data == value) {
  20. break;
  21. }
  22. /*
  23. if not,set `previousnode` to `currentnode`
  24. so that if the `value` is found in the next iteration
  25. we can use `previousnode` to remove the `node`
  26. */
  27. previousNode = currentNode;
  28. currentNode = currentNode.next;
  29. }
  30. /*
  31. if `value` is not in the list
  32. */
  33. if (currentNode == null) {
  34. console.log(`${value} is not in the list`);
  35. }
  36.  
  37. /*
  38. if `value` is in the list
  39. */
  40. else {
  41.  
  42. /*
  43. if it is the `head` of the list
  44. then set `head` of the list to
  45. `next` of `currentnode`
  46. */
  47.  
  48. if (currentNode.data == this.head.data) {
  49. this.head = currentNode.next;
  50.  
  51. }
  52. /*
  53. if not,point `next` of `previousnode`
  54. to `next` of `currentnode` so that `currentnode`
  55. will be removed from the list
  56. */
  57. else {
  58. previousNode.next = currentNode.next;
  59.  
  60. }
  61. /*
  62. decrement length
  63. */
  64. this.length--;
  65. console.log(`${value} is deleted from the list`);
  66. }
  67. }
  68. }
Add Comment
Please, Sign In to add comment