Skip to content

Instantly share code, notes, and snippets.

@kylemocode
Created March 10, 2020 05:40
Show Gist options
  • Save kylemocode/debc9b7746c28f47b2a9fbd04894c0bd to your computer and use it in GitHub Desktop.
Save kylemocode/debc9b7746c28f47b2a9fbd04894c0bd to your computer and use it in GitHub Desktop.
Linked List using TS
type LinkedNode = {
value: number,
next: LinkedNode | null
}
class LinkedList {
head: LinkedNode;
tail: LinkedNode;
length: number;
constructor(value: number) {
this.head = {
value: value,
next: null
};
this.tail = this.head;
this.length = 1;
}
append(value: number) {
const newNode: LinkedNode = {
value,
next: null
}
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value: number) {
const newNode: LinkedNode = {
value: value,
next: null
}
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
printList() {
const array: number[] = [];
let currentNode: LinkedNode = this.head;
while (currentNode !== null) {
array.push(currentNode.value);
currentNode = currentNode.next!;
}
return array;
}
insert(index: number, value: number) {
if (index >= this.length) {
console.log('yes')
return this.append(value);
}
const newNode: LinkedNode = {
value: value,
next: null
}
const leader = this.traverseToIndex(index - 1);
const holdingPointer = leader.next;
leader.next = newNode;
newNode.next = holdingPointer;
this.length++;
return this.printList();
}
traverseToIndex(index: number) {
let counter = 0;
let currentNode: LinkedNode = this.head;
while (counter !== index) {
currentNode = currentNode.next!;
counter++;
}
return currentNode;
}
remove(index: number) {
const leader = this.traverseToIndex(index - 1);
const unwantedNode: LinkedNode = leader.next!;
leader.next = unwantedNode.next;
this.length--;
return this.printList();
}
}
let myLinkedList = new LinkedList(10);
myLinkedList.append(5);
myLinkedList.append(16); myLinkedList.prepend(1);
myLinkedList.insert(2, 99);
myLinkedList.insert(20, 88);
myLinkedList.remove(2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment