您的位置:首页 > 产品设计 > UI/UE

[LeetCode]Implement Queue using Stacks

2015-07-19 08:59 197 查看
解题思路:
1,使用2个stack,一个叫PushStack,一个叫PopStack。
2,每当Queue新进来一个element时,就把它加入到PushStack,
3,当Queue执行Pop操作时,从PopStack取出element。
4,当PopStack为空时,把PushStack的元素一个一个的加入到PopStack

数据如何从pushStack到popStack
1,popStack必须为空,pushStack非空;
2,element = pushStack.top()
popStack.push(element)
pushStack.pop()
3,反复执行步骤2,直到pushStack为空

// 编译错误
1,Stack不是一个已经定义的类型。应该小写s的 stack

class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
pushStack.push(x);
}

// Removes the element from in front of queue.
void pop(void) {
if (empty()){
// EXCLUDE IN THIS PROBLEM
}
if (popStack.empty() && !pushStack.empty()){
tansportation();
}
return popStack.pop();
}

// Get the front element.
int peek(void) {
if (empty()){
// EXCLUDE IN THIS PROBLEM
}
if (popStack.empty() && !pushStack.empty()){
tansportation();
}
return popStack.top();
}

// Return whether the queue is empty.
bool empty(void) {
return pushStack.empty() && popStack.empty();
}

void tansportation(void){
if (popStack.empty() && !pushStack.empty()){
while(!pushStack.empty()){
int elem = pushStack.top();
popStack.push(elem);
pushStack.pop();
}
}
}
private:
stack<int> pushStack;
stack<int> popStack;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: