UNPKG

@wyfy/linked-list

Version:

A package that helps you create a simple linked list

104 lines (103 loc) 3.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkList = /** @class */ (function () { function LinkList() { var _this = this; /** * @remarks * Adds a new node from the tail, * every node is an object with id, value and next property, * @param value * Will be stored in the node's value property * @returns * The newly added node */ this.addNodeTail = function (value) { _this.length++; var node = { id: _this.length, value: value, next: null, }; if (!_this.head) { _this.head = node; return _this.head; } if (_this.head && !_this.head.next) { _this.tail = node; _this.head.next = node; return _this.tail; } ; _this.tail.next = node; _this.tail = node; return _this.tail; }; /** * @remarks * Adds a new node from the head, * every node is an object with id, value and next property * @param value * will be stored in the node's value property * @returns * The newly added node */ this.addNodeHead = function (value) { _this.length++; var node = { id: _this.length, value: value, next: null, }; if (!_this.head) { _this.head = node; return _this.head; } if (_this.head && !_this.head.next) { _this.tail = _this.head; _this.head = node; _this.head.next = _this.tail; return _this.head; } var tempHead = _this.head; _this.head = node; _this.head.next = tempHead; return _this.head; }; this.findNode = function (id) { if (_this.length === 0) return 'List is empty'; var currentNode = _this.head; for (var index = 0; index < _this.length; index++) { if (currentNode.id === id) { return currentNode; } currentNode = currentNode.next; } }; this.deleteNode = function (id) { if (_this.length === 0) return 'List is empty'; var currentNode = _this.head; var prevNode = null; for (var index = 0; index < _this.length; index++) { if (currentNode.id === id) { _this.length--; if (prevNode) { prevNode.next = currentNode.next; return currentNode; } _this.head = currentNode.next; return currentNode; } prevNode = currentNode; currentNode = currentNode.next; } }; this.head = null; this.tail = null; this.length = 0; } return LinkList; }()); exports.default = LinkList;