Created
May 24, 2018 03:18
-
-
Save leozhang2018/6d4397de84e04d9f3c5c6a2b7681fee0 to your computer and use it in GitHub Desktop.
stacks to 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
function Queue(){ | |
var items = []; | |
function Stack() { | |
var item = []; | |
this.push = function (elem) { | |
item.push(elem); | |
return item; | |
}; | |
this.pop = function () { | |
return item.pop(); | |
}; | |
this.isEmpty = function () { | |
return item.length === 0; | |
}; | |
this.get = function () { | |
return item; | |
}; | |
} | |
var stack1 = new Stack(); | |
var stack2 = new Stack(); | |
this.push = function (elem) { | |
stack1.push(elem); | |
return items.push(elem); | |
} | |
this.pop = function () { | |
if(stack1.isEmpty() && stack2.isEmpty()){ | |
throw new Error("空队列"); | |
} | |
if(stack2.isEmpty() && !stack1.isEmpty()){ | |
while(!stack1.isEmpty()){ | |
stack2.push(stack1.pop()); | |
} | |
return stack2.pop(); | |
} | |
}; | |
this.get = function () { | |
if(!stack2.isEmpty()){ | |
return stack2.get().reverse(); | |
}else{ | |
return items; | |
} | |
} | |
} | |
var queue = new Queue(); | |
queue.push(0); | |
queue.push(1); | |
queue.push(2); | |
queue.get(); | |
queue.pop(); | |
queue.get(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment