DoublyLinkedList.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. "use strict";
  2. /**
  3. * A Doubly Linked List, because there aren't enough in the world...
  4. * this is pretty much a direct JS port of the one wikipedia
  5. * https://en.wikipedia.org/wiki/Doubly_linked_list
  6. *
  7. * For most usage 'insertBeginning' and 'insertEnd' should be enough
  8. *
  9. * nodes are expected to something like a POJSO like
  10. * {
  11. * prev: null,
  12. * next: null,
  13. * something: 'whatever you like'
  14. * }
  15. */
  16. class DoublyLinkedList {
  17. constructor() {
  18. this.head = null;
  19. this.tail = null;
  20. this.length = 0;
  21. }
  22. insertBeginning(node) {
  23. if (this.head === null) {
  24. this.head = node;
  25. this.tail = node;
  26. node.prev = null;
  27. node.next = null;
  28. this.length++;
  29. } else {
  30. this.insertBefore(this.head, node);
  31. }
  32. }
  33. insertEnd(node) {
  34. if (this.tail === null) {
  35. this.insertBeginning(node);
  36. } else {
  37. this.insertAfter(this.tail, node);
  38. }
  39. }
  40. insertAfter(node, newNode) {
  41. newNode.prev = node;
  42. newNode.next = node.next;
  43. if (node.next === null) {
  44. this.tail = newNode;
  45. } else {
  46. node.next.prev = newNode;
  47. }
  48. node.next = newNode;
  49. this.length++;
  50. }
  51. insertBefore(node, newNode) {
  52. newNode.prev = node.prev;
  53. newNode.next = node;
  54. if (node.prev === null) {
  55. this.head = newNode;
  56. } else {
  57. node.prev.next = newNode;
  58. }
  59. node.prev = newNode;
  60. this.length++;
  61. }
  62. remove(node) {
  63. if (node.prev === null) {
  64. this.head = node.next;
  65. } else {
  66. node.prev.next = node.next;
  67. }
  68. if (node.next === null) {
  69. this.tail = node.prev;
  70. } else {
  71. node.next.prev = node.prev;
  72. }
  73. node.prev = null;
  74. node.next = null;
  75. this.length--;
  76. }
  77. // FIXME: this should not live here and has become a dumping ground...
  78. static createNode(data) {
  79. return {
  80. prev: null,
  81. next: null,
  82. data: data
  83. };
  84. }
  85. }
  86. module.exports = DoublyLinkedList;