{
class Node {
data: any;
next: Node | null;
constructor(value: any) {
this.data = value;
this.next = null
}
}
class LinkedList {
head: Node;
constructor() {
this.head = new Node('head');
}
getLength() {
let length = 0;
let currentNode = this.head;
while (currentNode.next !== null) {
currentNode = currentNode.next;
length++;
}
return length;
}
append(newValue: any) {
const newNode = new Node(newValue);
let currentNode = this.head;
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
}
insertAfterNode(value: any, newValue: any) {
const newNode = new Node(newValue);
let currentNode = this.getNodeForData(value);
if (!currentNode) {
throw new Error('The specified node does not exist!');
}
newNode.next = currentNode.next;
currentNode.next = newNode;
}
getNodeForData(value: any) {
let currentNode = this.head;
if (!currentNode.next) {
throw new Error('The current list is empty!');
}
while (currentNode.next) {
currentNode = currentNode.next;
if (currentNode.data === value) {
return currentNode;
}
}
console.error('The node was not found!');
return null;
}
getNodeIndex(value: any) {
let currentNode = this.head;
if (!currentNode.next) {
throw new Error('The current list is empty!');
}
let index = 0;
while (currentNode.next) {
currentNode = currentNode.next;
if (currentNode.data === value) {
return index;
}
index++;
}
return -1;
}
removeNodeForData(value: any) {
let currentNode = this.getNodeForData(value);
if (!currentNode) {
throw new Error('The node to be deleted does not exist!');
}
const prevNode = this.getPrevNode(value);
if (!currentNode.next) {
prevNode.next = null;
} else {
prevNode.next = currentNode.next;
}
}
getPrevNode(value: any) {
let currentNode = this.head;
if (!currentNode.next) {
throw new Error('The current list is empty!');
}
if (currentNode.data === value) {
throw new Error('The current node is the head node!');
}
while (currentNode.next.data !== value) {
currentNode = currentNode.next;
if (!currentNode || !currentNode.next) {
throw new Error('The node was not found!');
}
}
return currentNode;
}
print() {
let currentNode = this.head;
while (currentNode.next) {
console.log(currentNode.next.data);
currentNode = currentNode.next;
}
}
reverse() {
let currentNode = this.head;
if (!currentNode.next) {
throw new Error('The current list is empty!');
}
let isFirst = true;
let lastNode: Node | null = null;
let newNode: Node | null = null;
while (currentNode.next) {
currentNode = currentNode.next;
newNode = Object.assign({
}, currentNode);
if (isFirst) {
newNode.next = null;
isFirst = false;
} else {
newNode.next = lastNode;
}
lastNode = Object.assign({
}, newNode);
}
this.head.next = lastNode;
}
sortByAsc() {
let currentNode = this.head;
if (!currentNode.next) {
throw new Error('The current list is empty!');
}
}
}
const node = new LinkedList();
node.append(4);
node.append(3);
node.append(6);
node.append(7);
node.append(9);
node.append(2);
node.reverse();
node.print();
}