Skip to content

Instantly share code, notes, and snippets.

@konami99
Created February 8, 2024 21:07
Show Gist options
  • Save konami99/d0165dfcb2ea5735a10288be9d35bb9f to your computer and use it in GitHub Desktop.
Save konami99/d0165dfcb2ea5735a10288be9d35bb9f to your computer and use it in GitHub Desktop.
doubly Linked List
class NodeP<T> {
value: T;
previous: NodeP<T> | undefined;
next: NodeP<T> | undefined;
constructor(value: T) {
this.value = value;
}
}
class DoublyLinkedList<T> {
start: NodeP<T> | undefined;
end: NodeP<T> | undefined;
constructor(firstNode?: NodeP<T>, lastNode?: NodeP<T>) {
this.start = firstNode;
this.end = lastNode;
}
insertAtEnd(value: T) {
var newNode = new NodeP<T>(value)
if (!this.start) {
this.start = newNode;
this.end = newNode;
return;
}
newNode.previous = this.end;
this.end!.next = newNode;
this.end = newNode;
}
removeFromHead() {
var removedNode = this.start;
this.start = removedNode!.next;
return removedNode;
}
}
class Queue<T> {
linkedList: DoublyLinkedList<T>;
constructor() {
this.linkedList = new DoublyLinkedList<T>();
}
enqueue(value: T) {
this.linkedList.insertAtEnd(value);
}
dequeue(): T | undefined {
return this.linkedList.removeFromHead()?.value;
}
read(): T | undefined {
return this.linkedList.start?.value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment