Skip to content

Instantly share code, notes, and snippets.

@konami99
Created February 8, 2024 21:06
Show Gist options
  • Save konami99/4a5298101d45fcad815f995faafa57e2 to your computer and use it in GitHub Desktop.
Save konami99/4a5298101d45fcad815f995faafa57e2 to your computer and use it in GitHub Desktop.
linked list
class NodePoint<T> {
value: T;
next: NodePoint<T> | null;
constructor(value: T) {
this.value = value;
this.next = null;
}
}
class LinkedList<T> {
first: NodePoint<T> | null;
constructor(firstNode: NodePoint<T>) {
this.first = firstNode;
}
indexOf(value: T): number {
var currentIndex = 0;
var currentNode = this.first;
if (currentNode?.value === value) {
return currentIndex;
}
while (currentNode!.next) {
currentNode = currentNode!.next;
currentIndex += 1;
if (currentNode.value === value) {
return currentIndex;
}
}
return -1;
}
read(index: number): T {
var currentIndex = 0;
var currentNode = this.first;
while (currentIndex < index) {
currentIndex += 1;
currentNode = currentNode!.next;
}
return currentNode!.value;
}
insertAtIndex(index: number, value: T): void {
const newNodePoint = new NodePoint<T>(value);
if (index === 0) {
newNodePoint.next = this.first;
this.first = newNodePoint;
return;
}
var currentNode = this.first;
var currentIndex = 0;
while (currentIndex < (index - 1)) {
currentNode = currentNode!.next;
currentIndex += 1;
}
newNodePoint.next = currentNode!.next;
currentNode!.next = newNodePoint;
}
deleteAtIndex(index: number) {
var currentIndex = 0;
var currentNode = this.first;
if (index === 0) {
this.first = currentNode!.next;
return;
}
while (currentIndex < (index - 1)) {
currentNode = currentNode!.next;
currentIndex += 1;
}
currentNode!.next = currentNode!.next!.next;
}
}
var firstNode = new NodePoint<number>(3);
var secondNode = new NodePoint<number>(5);
var thirdNode = new NodePoint<number>(8);
firstNode.next = secondNode;
secondNode.next = thirdNode;
//console.log(firstNode.next);
//console.log(secondNode.next);
var linkedList = new LinkedList<number>(firstNode);
linkedList.insertAtIndex(2, 99)
//console.log(firstNode.next);
//console.log(secondNode.next);
const num = linkedList.read(2);
console.log(num);
const num1 = linkedList.indexOf(99);
console.log(num1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment