Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. class Node {
  2. constructor(value, next = null) {
  3. this.value = value;
  4. this.next = next;
  5. }
  6. }
  7.  
  8.  
  9. class SLL {
  10. constructor() {
  11. this.head = null;
  12. this.tail = null;
  13. this.length = 0;
  14. }
  15.  
  16. add(value) {
  17. const node = new Node(value);
  18. let currentNode = this.head;
  19.  
  20. if (!currentNode) {
  21. this.head = node;
  22. this.tail = node;
  23. this.length++;
  24.  
  25. return node;
  26. } else {
  27. while (currentNode.next) {
  28. currentNode = currentNode.next
  29. }
  30. currentNode.next = node;
  31. this.tail = node;
  32. this.length++;
  33. return node;
  34. }
  35. }
  36.  
  37. traverse() {
  38. let currentNode = this.head;
  39. for (let i = 0; i < this.length; i++) {
  40. console.log(currentNode.value);
  41. currentNode = currentNode.next;
  42. }
  43. }
  44. remove(location) {
  45. if (location === 0) { // we want to delete first element
  46. this.head = this.head.next;
  47. this.length--;
  48. if (this.length === 0) { // if there are no more nodes in this list
  49. this.tail = null;
  50. }
  51. } else { //if any inside node is to be deleted
  52. let currentNode = this.head;
  53. for (let i = 0; i < location - 1; i++) {
  54. currentNode = currentNode.next; // we need to traverse till we find the location
  55. }
  56. currentNode.next = currentNode.next.next; // delete the required node
  57. this.tail = currentNode;
  58. this.length--;
  59. } //end of else
  60.  
  61. }
  62. }
  63.  
  64. const node = new SLL();
  65.  
  66. node.add(5);
  67. node.add(9);
  68. node.add(15);
  69. node.traverse();
  70. // console.log(JSON.stringify(node, 0, 2))
  71. // node.remove(2);
  72. // console.log(JSON.stringify(node, 0, 2))
  73. // node.remove(1);
  74. // console.log(JSON.stringify(node, 0, 2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement