linked-list-lib
Version:
This package contain some possibilities of implementations of linked lists
85 lines (84 loc) • 2.5 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CircularSinglyLinkedList = void 0;
const comparator_1 = require("../comparator");
const singly_linked_list_1 = require("../singly-linked-list/singly-linked-list");
class CircularSinglyLinkedList extends singly_linked_list_1.SinglyLinkedList {
constructor(comparator = new comparator_1.Comparator()) {
super(comparator);
this.comparator = comparator;
}
insertInBegin(data) {
const node = super.insertInBegin(data);
if (!this.head.next) { // 1 node
this.head.next = this.head;
}
this.tail.next = this.head;
return node;
}
deleteNode(data) {
if (this.isEmpty()) {
return null;
}
this.tail.next = null;
let node = super.deleteNode(data);
if (this.tail) {
this.tail.next = this.head;
}
return node;
}
deleteFirstNode() {
if (this.isEmpty()) {
return null;
}
this.tail.next = null;
let node = super.deleteFirstNode();
if (this.tail) {
this.tail.next = this.head;
}
return node;
}
deleteLastNode() {
if (this.isEmpty()) {
return null;
}
this.tail.next = null;
let node = super.deleteLastNode();
if (this.tail) {
this.tail.next = this.head;
}
return node;
}
traverse() {
if (this.isEmpty()) {
return [];
}
const array = [];
this.tail.next = null;
const addToArray = (node) => {
array.push(node.data);
return (node.next) ? addToArray(node.next) : array;
};
const result = addToArray(this.head);
this.tail.next = this.head;
return result;
}
print(referenceProperty) {
if (this.isEmpty()) {
return 'NULL';
}
let str = '[HEAD]:';
this.tail.next = null;
const addToString = (node) => {
str += (node.data instanceof Object) ?
`${node.data[referenceProperty]}` :
`${node.data}`;
str += ' -> ';
return (node.next) ? addToString(node.next) : `${str}[HEAD]`;
};
const result = addToString(this.head);
this.tail.next = this.head;
return result;
}
}
exports.CircularSinglyLinkedList = CircularSinglyLinkedList;