您的位置:首页 > 编程语言 > C语言/C++

利用两个栈实现一个队列(C++版)

2015-11-25 23:45 971 查看
题目:

利用两个栈实现一个队列的功能,完成pop() push() peek() empty()等功能。

push(x) -- Push element x to the back of queue.

pop() -- Removes the element from in front of queue.

peek() -- Get the front element.

empty() -- Return whether the queue is empty.

主要思想:一个栈作为压入栈(只执行push操作),另一个栈作为弹出栈(只执行pop操作)。

push —— 执行压入操作时,将数据压入 压入栈。

pop —— 执行弹出操作时,必须将压入栈所有的数据压入弹出栈,然后取出弹出栈顶元素。

peek —— 只获取弹出栈栈顶元素 不弹出。

empty —— 只有两个栈都为空才返回true

实现函数代码如下:

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

// Removes the element from in front of queue.
void pop(void) {
if(stackPop.empty() && !stackPush.empty())
{
while(!stackPush.empty())
{
stackPop.push(stackPush.top());
stackPush.pop();
}
}
stackPop.pop();
}

// Get the front element.
int peek(void) {
if(stackPop.empty() && !stackPush.empty())
{
while(!stackPush.empty())
{
stackPop.push(stackPush.top());
stackPush.pop();
}
}

return stackPop.top();
}

// Return whether the queue is empty.
bool empty(void) {
if(stackPush.empty() && stackPop.empty() )
{
return true;
}

return false;
}
public:
stack<int> stackPush;
stack<int> stackPop;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: