Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created July 20, 2020 17:19
Show Gist options
  • Save karol-majewski/57db85d762b0197bc2fbe2e6c52c66d8 to your computer and use it in GitHub Desktop.
Save karol-majewski/57db85d762b0197bc2fbe2e6c52c66d8 to your computer and use it in GitHub Desktop.
class Node {
next: Node | null = null;
constructor(readonly data: number) {}
}
class LinkedList {
head: Node | null = null;
append(data: number): void {
if (this.head === null) {
this.head = new Node(data);
return;
}
let current: Node = this.head;
while (current.next !== null) {
current = current.next
}
current.next = new Node(data);
}
prepend(data: number): void {
const newHead: Node = new Node(data);
newHead.next = this.head;
this.head = newHead;
}
deleteNode(data: number): void {
if (this.head === null) {
return;
}
if (this.head.data === data) {
this.head = this.head.next;
return;
}
let current: Node = this.head;
while (current.next !== null) {
if (current.next.data === data) {
current.next = current.next.next;
return
}
current = current.next
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment