Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DoublyLinkedList.js 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 = function () {
  26. while (this.head) this.shift();
  27. return this;
  28. };
  29. DLL.prototype.insertAfter = function (node, newNode) {
  30. newNode.prev = node;
  31. newNode.next = node.next;
  32. if (node.next) node.next.prev = newNode;else this.tail = newNode;
  33. node.next = newNode;
  34. this.length += 1;
  35. };
  36. DLL.prototype.insertBefore = function (node, newNode) {
  37. newNode.prev = node.prev;
  38. newNode.next = node;
  39. if (node.prev) node.prev.next = newNode;else this.head = newNode;
  40. node.prev = newNode;
  41. this.length += 1;
  42. };
  43. DLL.prototype.unshift = function (node) {
  44. if (this.head) this.insertBefore(this.head, node);else setInitial(this, node);
  45. };
  46. DLL.prototype.push = function (node) {
  47. if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node);
  48. };
  49. DLL.prototype.shift = function () {
  50. return this.head && this.removeLink(this.head);
  51. };
  52. DLL.prototype.pop = function () {
  53. return this.tail && this.removeLink(this.tail);
  54. };
  55. DLL.prototype.toArray = function () {
  56. var arr = Array(this.length);
  57. var curr = this.head;
  58. for (var idx = 0; idx < this.length; idx++) {
  59. arr[idx] = curr.data;
  60. curr = curr.next;
  61. }
  62. return arr;
  63. };
  64. DLL.prototype.remove = function (testFn) {
  65. var curr = this.head;
  66. while (!!curr) {
  67. var next = curr.next;
  68. if (testFn(curr)) {
  69. this.removeLink(curr);
  70. }
  71. curr = next;
  72. }
  73. return this;
  74. };
  75. module.exports = exports["default"];