class Node {
constructor(data, next = null, previous = null) {
this.data = data;
this.next = next;
this.previous = previous;
}
}
class linkedList {
constructor(head = null, tail = null) {
this.head = head;
this.tail = tail;
this.size = 0;
}
appendAtlast(data) {
let node = new Node(data);
if (this.head === null) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
node.previous = this.tail;
this.tail = node;
}
this.size++;
}
addAtFirst(data) {
let node = new Node(data);
if (this.head === null) {
this.head = node;
} else {
this.head.previous = node;
node.next = this.head;
this.head = node;
}
this.size++;
}
addAtIndex(data, index) {
let node = new Node(data);
if (index === 0) {
this.addAtFirst(data);
return;
}
if (index >= this.size) {
return;
}
let count = 0;
let current;
while (count < index) {
current = current.next;
count++;
}
const previousNode = current.previous;
previousNode.next = node;
node.next = current;
node.previous = previousNode;
current.previous = node;
this.size++;
}
remove() {
if (this.tail) {
this.size--;
this.tail = this.tail.previous;
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
} else {
this.head = null;
}
}
removeAtIndex(index) {
if (!Number.isInteger(index) || index < 0 || index > this.sixe) {
console.log(`Invalid index. Current length is ${this.size}.`);
return this;
}
if (index === 0) {
this.head = this.head.next;
this.head.previous = null;
this.size--;
return;
}
if (index === this.size - 1) {
this.tail = this.tail.previous;
this.tail.next = null;
this.size--;
return;
}
let count = 0;
let current = this.head;
while (count < index) {
current = current.next;
count++;
}
const previousNode = current.previous;
const nextNode = current.next;
previousNode.next = nextNode;
nextNode.previous = previousNode;
this.size--;
}
print() {
let current = this.head;
console.log("Size", this.size);
while (current) {
console.log(` ${current.data}`);
current = current.next;
}
}
}
let ll = new linkedList();
ll.appendAtlast(100);
ll.appendAtlast(200);
ll.addAtFirst(99);
ll.appendAtlast(300);
ll.removeAtIndex(3);
ll.appendAtlast(300);
ll.remove();
ll.print();