Last active
August 29, 2015 14:15
-
-
Save forrestbthomas/2aa01406f72e4072707c to your computer and use it in GitHub Desktop.
Typescript Stack
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 { | |
pop(): number; | |
push(value: number): void; | |
peek(): number; | |
isEmpty(): boolean; | |
} | |
class Stack implements Collection { | |
value: number; | |
pointer: any; | |
pop() { | |
var next = this.pointer; | |
var result = null; | |
if (this.pointer === null) { | |
result = this.value; | |
this.value = null; | |
return result; | |
} else { | |
result = this.pointer.value; | |
this.pointer = this.pointer.pointer; | |
return result; | |
} | |
} | |
push(value: number) { | |
var previousPointer = this.pointer; | |
var nextNode = new Stack(value); | |
if (!this.pointer) { | |
this.pointer = nextNode; | |
} else { | |
this.pointer = nextNode; | |
nextNode.pointer = previousPointer; | |
} | |
} | |
peek() { | |
var next = this.pointer; | |
if (this.pointer === null) { | |
return this.value; | |
} else { | |
return this.pointer.value; | |
} | |
} | |
isEmpty() { | |
if (this.pointer === null) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
constructor(value: number) { | |
this.value = value; | |
this.pointer = null; | |
} | |
} | |
var stack1 = new Stack(1); | |
stack1.push(3); | |
stack1.push(5); | |
stack1.pop(); | |
console.log(stack1.isEmpty()); | |
stack1.pop(); | |
console.log(stack1.peek()); | |
stack1.pop(); | |
console.log(stack1.isEmpty()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment