tstruct
Version:
Data structures & basic algorithms library
118 lines (117 loc) • 3.7 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LinkedList = exports.ILinkedListNode = void 0;
var ILinkedListNode = (function () {
function ILinkedListNode(val, next) {
this.val = val;
this.next = next;
}
return ILinkedListNode;
}());
exports.ILinkedListNode = ILinkedListNode;
var LinkedList = (function () {
function LinkedList() {
this._length = 0;
}
Object.defineProperty(LinkedList.prototype, "head", {
get: function () {
return this._head;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LinkedList.prototype, "tail", {
get: function () {
return this._tail;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LinkedList.prototype, "isEmpty", {
get: function () {
return this.size == 0;
},
enumerable: false,
configurable: true
});
LinkedList.prototype.add = function (val) {
var node = new ILinkedListNode(val);
if (!this._head) {
this._head = node;
this._tail = node;
}
else {
this._tail.next = node;
this._tail = node;
}
this._length++;
};
LinkedList.prototype.getNode = function (index) {
if (index < 0 || index >= this.size) {
return undefined;
}
var currentIndex = 0;
var currentNode = this._head;
while (currentIndex < index && currentNode) {
currentNode = currentNode === null || currentNode === void 0 ? void 0 : currentNode.next;
currentIndex++;
}
return currentNode;
};
LinkedList.prototype.get = function (index) {
var _a;
return (_a = this.getNode(index)) === null || _a === void 0 ? void 0 : _a.val;
};
LinkedList.prototype.remove = function (index) {
var _a, _b;
if (index < 0 || index >= this.size || this.size == 0)
return;
if (index == 0 && this.size == 1) {
this._head = undefined;
this._tail = undefined;
}
else if (index == 0) {
this._head = (_a = this._head) === null || _a === void 0 ? void 0 : _a.next;
}
else if (index == this._length - 1) {
var node = this.getNode(index - 1);
node.next = undefined;
this._tail = node;
}
else {
var node = this.getNode(index - 1);
node.next = (_b = node === null || node === void 0 ? void 0 : node.next) === null || _b === void 0 ? void 0 : _b.next;
}
this._length--;
};
Object.defineProperty(LinkedList.prototype, "size", {
get: function () {
return this._length;
},
enumerable: false,
configurable: true
});
LinkedList.prototype[Symbol.iterator] = function () {
var node = this._head;
return {
next: function () {
if (node) {
var val = node.val;
node = node.next;
return {
done: false,
value: val,
};
}
else {
return {
done: true,
value: null,
};
}
},
};
};
return LinkedList;
}());
exports.LinkedList = LinkedList;