Skip to content

Instantly share code, notes, and snippets.

@forrestbthomas
Created February 22, 2015 04:21
Show Gist options
  • Save forrestbthomas/7450e2b90a0cfbd10eaf to your computer and use it in GitHub Desktop.
Save forrestbthomas/7450e2b90a0cfbd10eaf to your computer and use it in GitHub Desktop.
Typescript Queue
interface Collection {
push(value: number): void;
pop(): number;
peek(): number;
isEmpty(): boolean;
}
class Node {
value: number;
constructor(value: number) {
this.value = value;
}
}
class Queue implements Collection {
pointer: any;
rear: any;
constructor(value: number) {
this.pointer = null;
this.rear = null;
}
push(value: number) {
var pushedNode = new Node(value);
var previousRear = this.rear;
if (!this.rear) {
this.pointer = pushedNode;
this.rear = pushedNode;
} else {
this.rear = pushedNode;
previousRear.pointer = pushedNode;
}
}
pop() {
var poppedValue = this.pointer.value;
this.pointer = this.pointer.pointer;
if (!this.pointer) {
this.rear = null;
}
return poppedValue;
}
peek() {
if (this.pointer) {
return this.pointer.value;
} else {
return undefined;
}
}
isEmpty() {
return this.rear === null;
}
}
var queue = new Queue();
queue.push(1);
queue.push(2);
queue.push(3);
queue.pop();
queue.pop();
queue.pop();
console.log(queue)
console.log(queue.peek())
console.log(queue.isEmpty())
@RedWrath5
Copy link

Don't know why the constructor for Queue takes a value, but thanks for laying the groundwork.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment