Skip to content

Instantly share code, notes, and snippets.

@segaz2002
Created December 4, 2021 20:31
Show Gist options
  • Save segaz2002/b91e68b11a1e3c2b0bbc3f7a8d142baa to your computer and use it in GitHub Desktop.
Save segaz2002/b91e68b11a1e3c2b0bbc3f7a8d142baa to your computer and use it in GitHub Desktop.
Create a stack with a Queue
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