DoublyLinkedList.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = DLL;
  6. // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
  7. // used for queues. This implementation assumes that the node provided by the user can be modified
  8. // to adjust the next and last properties. We implement only the minimal functionality
  9. // for queue support.
  10. function DLL() {
  11. this.head = this.tail = null;
  12. this.length = 0;
  13. }
  14. function setInitial(dll, node) {
  15. dll.length = 1;
  16. dll.head = dll.tail = node;
  17. }
  18. DLL.prototype.removeLink = function (node) {
  19. if (node.prev) node.prev.next = node.next;else this.head = node.next;
  20. if (node.next) node.next.prev = node.prev;else this.tail = node.prev;
  21. node.prev = node.next = null;
  22. this.length -= 1;
  23. return node;
  24. };
  25. DLL.prototype.empty = DLL;
  26. DLL.prototype.insertAfter = function (node, newNode) {
  27. newNode.prev = node;
  28. newNode.next = node.next;
  29. if (node.next) node.next.prev = newNode;else this.tail = newNode;
  30. node.next = newNode;
  31. this.length += 1;
  32. };
  33. DLL.prototype.insertBefore = function (node, newNode) {
  34. newNode.prev = node.prev;
  35. newNode.next = node;
  36. if (node.prev) node.prev.next = newNode;else this.head = newNode;
  37. node.prev = newNode;
  38. this.length += 1;
  39. };
  40. DLL.prototype.unshift = function (node) {
  41. if (this.head) this.insertBefore(this.head, node);else setInitial(this, node);
  42. };
  43. DLL.prototype.push = function (node) {
  44. if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node);
  45. };
  46. DLL.prototype.shift = function () {
  47. return this.head && this.removeLink(this.head);
  48. };
  49. DLL.prototype.pop = function () {
  50. return this.tail && this.removeLink(this.tail);
  51. };
  52. module.exports = exports["default"];