Last active
August 29, 2015 14:24
-
-
Save joshbedo/743f090f6b939725572b to your computer and use it in GitHub Desktop.
Queues (FIFO) and Stacks (LIFO)
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 Node { | |
constructor(data) { | |
this.data = data; | |
this.previous = null; | |
} | |
} | |
class Stack { | |
constructor() { | |
this.top = null; | |
this.size = 0; | |
} | |
push(data) { | |
var node = new Node(data); | |
node.previous = this.top; | |
this.top = node; | |
this.size++; | |
return this.top; | |
} | |
pop() { | |
var tmp = this.top; | |
this.top = this.top.previous; | |
this.size--; | |
return tmp.data; | |
} | |
size() { | |
return this.size; | |
} | |
} | |
//var s1 = new Stack(); | |
//s1.push('something'); | |
//s1.push('something else'); | |
//s1.pop(); | |
class Queue { | |
constructor() { | |
var s1 = new Stack(), | |
s2 = new Stack(); | |
this.enqueue = function(item) { | |
s1.push(item); | |
}; | |
this.dequeue = function() { | |
if (s1.size == 0 && s2.size == 0) { | |
return console.log('stacks are empty can\'t dequeue'); | |
} | |
while(s1.size) { | |
s2.push(s1.pop()); | |
} | |
console.log('item dequeued', s2.pop()); | |
}; | |
this.showStacks = function() { | |
console.log('stack1', (s1.top) ? s1.top.data : s1.top); | |
console.log('stack2', (s2.top) ? s2.top.data : s2.top); | |
} | |
} | |
} | |
var myQueue = new Queue(); | |
myQueue.dequeue(); | |
myQueue.enqueue(1); | |
myQueue.showStacks(); | |
myQueue.dequeue(); | |
myQueue.showStacks(); | |
myQueue.enqueue(1); | |
myQueue.enqueue(2); | |
myQueue.dequeue(); | |
myQueue.showStacks(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment