Created
February 8, 2024 21:07
-
-
Save konami99/d0165dfcb2ea5735a10288be9d35bb9f to your computer and use it in GitHub Desktop.
doubly Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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