Zhorzh

Untitled

Mar 8th, 2022
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. import LinkedListNode from './linked-list-node.js';
  2.  
  3. export default class DoublyLinkedList {
  4. #head = null;
  5. #tail = null;
  6. #count = 0;
  7. constructor(){
  8. this.#head=null;
  9. this.#tail=null;
  10. this.#count=0;
  11. }
  12. get count() {
  13. return this.#count;
  14. }
  15. get head() {
  16. return this.#head;
  17. }
  18. get tail() {
  19. return this.#tail;
  20. }
  21. get isEmpty() {
  22. return !this.#head;
  23. }
  24. addFirst(value) {
  25. const node = new LinkedListNode(value);
  26. if (this.isEmpty) {
  27. this.#head = node;
  28. this.#tail = this.#head;
  29. } else {
  30. node.next = this.#head;
  31. this.#head = node;
  32. }
  33. this.#count = this.#count + 1;
  34. }
  35. addLast(value) {
  36. const node = new LinkedListNode(value);
  37. if (this.isEmpty) {
  38. this.#head = node;
  39. this.#tail = node;
  40. } else {
  41. this.#tail.next = node;
  42. this.#tail = this.#tail.next;
  43. }
  44. this.#count = this.#count + 1;
  45. }
  46. removeFirst() {
  47. if (this.isEmpty){
  48. throw new Error('node empty');
  49. }
  50. const value = this.#head.value;
  51. this.#head = this.#head.next;
  52. this.#count--;
  53. return value;
  54. }
  55. removeLast() {
  56. if (this.isEmpty){
  57. throw new Error('node empty');
  58. }
  59. const value = this.#tail.value;
  60. this.#tail = this.#tail.prev;
  61. this.#count--;
  62. return value;
  63. }
  64. insertBefore(node, value) {
  65.  
  66. this.#count++;
  67. const newNode = new LinkedListNode(value);
  68. if (node.value === this.#head.value) {
  69. this.#head.prev = newNode;
  70. newNode.next = this.#head;
  71. this.#head = newNode;
  72. }
  73. newNode.prev = node.prev;
  74. node.prev.next = newNode;
  75. newNode.next = node;
  76. }
  77. insertAfter(node, value) {
  78. if(node === null){
  79. throw new Error('the given node cannot be null');
  80. }
  81. const newNode = new LinkedListNode(value);
  82. newNode.next = node.next;
  83. node.next = newNode;
  84. if(node === this.#tail){
  85. this.#tail.next = newNode;
  86. this.#tail=this.#tail.next;
  87. }
  88. this.#count++;
  89. }
  90. find(val) {
  91. let current = this.#head;
  92. let final = null;
  93. while(current){
  94. if(current.value === val) {
  95. final = current;
  96. }
  97. current =current.next;
  98. }
  99. return final;
  100. }
  101. values(){
  102. if(this.isEmpty){
  103. return [];
  104. }
  105. let current = this.#head;
  106. let final = [];
  107. while(current){
  108. final.push(current.value);
  109. current = current.next;
  110. }
  111. return final;
  112. }
  113. }
Advertisement
Add Comment
Please, Sign In to add comment