admin管理员组文章数量:1636972
As the title described, you should only use two stacks to implement a queue’s actions.
The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
Challenge
implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.
1.
在push上做文章,每次push前,将stack1中的元素依次弹到stack2,element push到stack2后,再将stack2依次弹到stack1.
这样pop和top的操作就是O(1)。
但push的复杂度比较高
class Queue {
public:
stack<int> stack1;
stack<int> stack2;
Queue() {
// do intialization if necessary
}
void push(int element) {
// write your code here
while(!stack1.empty()){
int top=stack1.top();
stack1.pop();
stack2.push(top);
}
stack2.push(element);
while(!stack2.empty()){
int top=stack2.top();
stack2.pop();
stack1.push(top);
}
}
int pop() {
// write your code here
int res=stack1.top();
stack1.pop();
return res;
}
int top() {
// write your code here
return stack1.top();
}
};
2.
push照常;
pop和top这样做:如果stack2不为空,pop stack2;否则将stack1中所有元素弹到stack2;
这样整体时间复杂度较低。
class Queue {
public:
stack<int> stack1;
stack<int> stack2;
Queue() {
// do intialization if necessary
}
void push(int element) {
// write your code here
stack1.push(element);
}
int pop() {
// write your code here
if(stack2.empty()){
pushInto2(stack1,stack2);
}
int res=stack2.top();
stack2.pop();
return res;
}
int top() {
// write your code here
if(stack2.empty()){
pushInto2(stack1,stack2);
}
return stack2.top();
}
private:
void pushInto2(stack<int> &stack1,stack<int> &stack2){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
};
版权声明:本文标题:Implement Queue by Two Stacks 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1729234866a1191875.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论