class CLLNode {
constructor(value) {
this._previous = this;
this._next = this;
this._value = value;
}
get previous() {
return this._previous;
}
set previous(value) {
this._previous = value;
}
get next() {
return this._next;
}
set next(value) {
this._next = value;
}
get value() {
return this._value;
}
set value(value) {
this._value = value;
}
}
class CircularLinkedList {
constructor() {
this._head = null;
this._tail = null;
this._length = 0;
}
get head() {
return this._head;
}
get tail() {
return this._tail;
}
get length() {
return this._length;
}
append(value) {
const newNode = new CLLNode(value);
if (!this._head) {
this._head = newNode;
this._tail = newNode;
return;
}
this._tail.next = newNode;
newNode.previous = this._tail;
this._tail = newNode;
newNode.next = this._head;
this._length++;
}
prepend(value) {
const newNode = new CLLNode(value);
if (!this._head) {
this._head = newNode;
this._tail = newNode;
return;
}
newNode.next = this._head;
this._head.previous = newNode;
this._head = newNode;
this._length++;
}
delete(value) {
if (!this._head) {
return;
}
while (this._head && this._head.value === value) {
this._head = this._head.next;
}
let currentNode = this._head;
while (currentNode.next) {
if (currentNode.next.value === value) {
currentNode.next = currentNode.next.next;
}
else {
currentNode = currentNode.next;
}
}
if (this._tail.value === value) {
this._tail = currentNode;
}
}
toArray() {
let index = 0;
const elements = [];
let currentNode = this._head;
while (currentNode) {
elements.push(currentNode.value);
currentNode = currentNode.next;
index++;
if (index > this._length) {
break;
}
}
return elements;
}
}
const cars = new CircularLinkedList();
cars.append({ make: 'Ford', model: 'Fiesta', year: 2010 });
cars.append({ make: 'Ford', model: 'Focus', year: 2011 });
cars.append({ make: 'Ford', model: 'Mustang', year: 2015 });
console.table(cars.toArray());
console.table(cars.head.value);