使用栈实现队列的下列操作:
- push(x) -- 将一个元素放入队列的尾部。
- pop() -- 从队列首部移除元素。
- peek() -- 返回队列首部的元素。
- empty() -- 返回队列是否为空。
解题思路:基本与用队列实现栈类似,返回头部元素的操作稍微麻烦一点。
class Solution {
private:
stack<int> Stack1, Stack2;
public:
void push(int x);
int pop(void);
int peek(void);
bool empty(void);
};
void Solution::push(int x)
{
Stack1.push(x);
}
int Solution::pop(void)
{
int number = Stack1.size();
int temp = 0;
unsigned int index = 0;
if(Stack1.empty() == true)
{
return false;
}
for(index = 0; index < number - 1; index ++)
{
Stack2.push(Stack1.top());
Stack1.pop();
}
temp = Stack1.top();
Stack1.pop();
for(index = 0; index < number - 1; index ++)
{
Stack1.push(Stack2.top());
Stack2.pop();
}
return temp;
}
int Solution::peek(void)
{
int number = Stack1.size();
int temp = 0;
unsigned int index = 0;
if(Stack1.empty() == true)
{
return false;
}
for(index = 0; index < number - 1; index ++)
{
Stack2.push(Stack1.top());
Stack1.pop();
}
temp = Stack1.top();
for(index = 0; index < number - 1; index ++)
{
Stack1.push(Stack2.top());
Stack2.pop();
}
return temp;
}
bool Solution::empty(void)
{
return Stack1.empty();
}