class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class SLList {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
pushLeft(data) {
const node = new Node(data);
node.next = this.head;
this.head = node;
if (this.size === 0) {
this.tail = node;
}
this.size++;
}
pushRight(data) {
if (this.size === 0) {
this.pushLeft(data);
return;
}
const node = new Node(data);
this.tail.next = node;
this.tail = node;
this.size++;
}
popLeft() {
if (this.size === 0) {
return;
}
const data = this.head.data;
this.head = this.head.next;
this.size--;
if (this.size === 0) {
this.tail = null;
}
return data;
}
popRight() {
if (this.size === 0) {
return;
}
if (this.size === 1) {
return this.popLeft();
}
let node = this.head;
while (node.next.next !== null) {
node = node.next;
}
const data = this.tail.data;
this.tail = node;
node.next = null;
this.size--;
}
reverse() {
if (this.size < 2) {
return;
}
let curr = this.head;
let prev = null;
let next = null;
while (curr !== null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
this.head = prev;
}
print() {
let output = "[ ";
let node = this.head;
while (node) {
output += node.data + " -> ";
node = node.next;
}
output += "null ]"
console.log(output);
}
}
const list = new SLList();
list.popLeft();
list.popRight();
list.pushLeft(2);
list.pushLeft(1);
list.pushRight(3);
list.pushRight(4);
list.pushRight(5);
list.print();
list.reverse();
list.print();
list.popLeft();
list.popLeft();
list.popRight();
list.popRight();
list.popRight();
console.log(list);
To embed this project on your website, copy the following code and paste it into your website's HTML: