Skip to content

Instantly share code, notes, and snippets.

@Lugriz
Created July 25, 2020 05:27
Show Gist options
  • Save Lugriz/4b478f75bae54425d9b0a8f95a5f804c to your computer and use it in GitHub Desktop.
Save Lugriz/4b478f75bae54425d9b0a8f95a5f804c to your computer and use it in GitHub Desktop.
Queue implementation
class Node {
public next: Node = null;
constructor(
public value: number
) {}
}
class Queue {
private front: Node = null;
private back: Node = null;
private length: number = 0;
public put(value: number): void {
const node = new Node(value);
this.length++;
if (this.isEmpty()) {
this.front = node;
this.back = node;
return;
}
this.back.next = node; // back = 1 -> 2 -> null
this.back = node;
}
public get(): number {
if(this.isEmpty()) {
return null;
}
const value = this.front.value;
this.front = this.front.next; // front = null | back = 2 -> null
this.length--;
if (this.isEmpty()) {
this.back = null;
}
return value;
}
public size(): number {
return this.length;
}
public isEmpty(): boolean {
return this.front === null;
}
}
const q = new Queue();
console.log('IS EMPTY:', q.isEmpty());
console.log('SIZE:', q.size());
q.put(1);
q.put(2);
q.put(3);
console.log('IS EMPTY:', q.isEmpty());
console.log('SIZE:', q.size());
console.log('GET:', q.get());
console.log('GET:', q.get());
console.log('IS EMPTY:', q.isEmpty());
console.log('SIZE:', q.size());
console.log('GET:', q.get());
console.log('IS EMPTY:', q.isEmpty());
console.log('SIZE:', q.size());
console.log(q);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment