@figliolia/data-structures
Version:
Efficient data structures for every day programming
116 lines (115 loc) • 2.84 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LinkedList = void 0;
class ListNode {
constructor(value, previous = null, next = null) {
this.previous = null;
this.next = null;
this.value = value;
this.next = next;
this.previous = previous;
}
}
/**
* Linked List
*
* A doubly linked list mimicking the interface of JavaScript arrays
*
* ```typescript
* import { LinkedList } from "@figliolia/data-structures";
*
* const list = new LinkedList<number>();
* list.push(1);
* list.push(2);
* list.push(3);
* for(const item of list) {
* console.log(item); // 1, 2, 3
* }
* list.pop(); // 3 -> O(1)
* list.shift() // 1 -> O(1)
* list.push(3) // O(1)
* list.unshift(1) // O(1)
* ```
*/
class LinkedList {
constructor(...items) {
this.size = 0;
this.head = null;
this.tail = null;
for (const item of items) {
this.push(item);
}
}
push(item) {
this.size++;
const node = new ListNode(item);
if (!this.head && !this.tail) {
this.head = node;
this.tail = node;
return this.size;
}
this.tail.next = node;
node.previous = this.tail;
this.tail = node;
return this.size;
}
unshift(item) {
this.size++;
const node = new ListNode(item);
if (!this.head && !this.tail) {
this.head = node;
this.tail = node;
return this.size;
}
this.head.previous = node;
node.next = this.head;
this.head = node;
return this.size;
}
shift() {
if (!this.head) {
return;
}
this.size--;
const node = this.head;
if (this.head === this.tail) {
this.head = null;
this.tail = null;
return node.value;
}
this.head = node.next;
this.head.previous = null;
return node.value;
}
pop() {
if (!this.tail) {
return;
}
this.size--;
const node = this.tail;
if (this.head === this.tail) {
this.head = null;
this.tail = null;
return node.value;
}
this.tail = node.previous;
this.tail.next = null;
return node.value;
}
peekLeft() {
var _a;
return (_a = this.head) === null || _a === void 0 ? void 0 : _a.value;
}
peekRight() {
var _a;
return (_a = this.tail) === null || _a === void 0 ? void 0 : _a.value;
}
*[Symbol.iterator]() {
let current = this.head;
while (current) {
yield current.value;
current = current.next;
}
}
}
exports.LinkedList = LinkedList;