LeetCode232-使用棧實現隊列
設計一個隊列,支持基本的隊列操作,這個隊列的內部存儲數據的結構爲棧,棧的方法只能包括push、top、pop、size、empty等標準的棧方法
使用棧實現隊列的下列操作:
push(x) -- 將一個元素放入隊列的尾部。
pop() -- 從隊列首部移除元素。
peek() -- 返回隊列首部的元素。
empty() -- 返回隊列是否爲空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
class MyQueue
{
public:
MyQueue()
{
void push(int x)
{
}
int pop()
{
}
int peek()
{
}
bool empty()
{
}
}
};
#include<iostream>
#include<stack>
using namespace std;
class MyQueue
{
public:
MyQueue()
{
}
void push(int x)
{
std::stack<int> temp_stack;
while(!_data.empty())
{
temp_stack.push(_data.top());
_data.pop();
}
temp_stack.push(x);
while(!temp_stack.empty())
{
_data.push(temp_stack.top());
temp_stack.pop();
}
}
int pop()
{
int x=_data.top(); //取棧頂元素,即爲隊列頭部元素
_data.pop();
return x;
}
int peek()
{
return _data.top();//返回棧頂元素,即爲直接範圍隊列頭部元素
}
bool empty()
{
return _data.empty();
}
private:
std::stack<int> _data;
};
int main()
{
MyQueue Q;
Q.push(1);
Q.push(2);
Q.push(3);
Q.push(4);
printf("%d\n",Q.peek());
Q.pop();
printf("%d\n",Q.peek());
return 0;
}
運行結果如圖所示: