UNPKG

dbl-linked-list-ds

Version:

A typescript based doubly linked list data structure

79 lines (78 loc) 1.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const LinkedListNode_1 = require("./LinkedListNode"); class LinkedList { constructor(...values) { this.length = 0; this.headN = undefined; this.tailN = undefined; for (const i of values) { this.add(i); } } add(val) { const node = new LinkedListNode_1.LinkedListNode(val); if (this.length === 0) { this.headN = node; } if (this.tailN === undefined) { this.tailN = node; } else { this.tailN.right = node; node.left = this.tailN; this.tailN = node; } this.length += 1; return node; } forEach(f, ctx) { let node = this.headN; while (node !== undefined) { f.call(ctx, node); node = node.right; } } head() { return this.headN; } pop() { const h = this.tail(); if (h !== undefined) { this.remove(h); return h.value; } } remove(n) { if (n.left !== undefined && n.right !== undefined) { n.left.right = n.right; n.right.left = n.left; } else if (n.left !== undefined) { this.tailN = n.left; n.left.right = undefined; } else if (n.right !== undefined) { this.headN = n.right; n.right.left = undefined; } else { this.tailN = undefined; this.headN = undefined; } if (this.length > 0) { this.length -= 1; } } shift() { const h = this.head(); if (h !== undefined) { this.remove(h); return h.value; } } tail() { return this.tailN; } } exports.LinkedList = LinkedList;