Created
December 4, 2021 20:31
-
-
Save segaz2002/b91e68b11a1e3c2b0bbc3f7a8d142baa to your computer and use it in GitHub Desktop.
Create a stack with a Queue
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
var Node = function(data){ | |
this.data = data; | |
this.next = null; | |
}; | |
var Queue = function(){ | |
this.head = null; | |
this.tail = null; | |
} | |
Queue.prototype.add = function(x) { | |
let node = new Node(x); | |
if(this.tail) this.tail.next = node; | |
if(this.head == null) this.head = node; | |
this.tail = node; | |
} | |
Queue.prototype.remove = function() { | |
let data = this.tail.data; | |
if(this.head == this.tail){ | |
this.head = null; | |
this.tail = null; | |
return data; | |
} | |
let current = this.head; | |
let previous = null; | |
while(current.next != null){ | |
previous = current; | |
current = current.next; | |
this.tail = previous; | |
} | |
this.tail.next = null; | |
return data; | |
} | |
var MyStack = function() { | |
this.queue = new Queue(); | |
}; | |
/** | |
* @param {number} x | |
* @return {void} | |
*/ | |
MyStack.prototype.push = function(x) { | |
this.queue.add(x); | |
}; | |
/** | |
* @return {number} | |
*/ | |
MyStack.prototype.pop = function() { | |
let data = this.queue.remove(); | |
return data; | |
}; | |
/** | |
* @return {number} | |
*/ | |
MyStack.prototype.top = function() { | |
if(this.queue.tail == null) return; | |
let data = this.queue.tail.data; | |
return data; | |
}; | |
/** | |
* @return {boolean} | |
*/ | |
MyStack.prototype.empty = function() { | |
return (this.queue.head == null) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment