Created
February 22, 2015 04:21
-
-
Save forrestbthomas/7450e2b90a0cfbd10eaf to your computer and use it in GitHub Desktop.
Typescript Queue
This file contains 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
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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't know why the constructor for Queue takes a value, but thanks for laying the groundwork.