1、題目描述
使用隊列實現棧的下列操作:
push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否爲空
注意:
- 你只能使用隊列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。
- 你所使用的語言也許不支持隊列。 你可以使用 list 或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。
- 你可以假設所有操作都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操作)。
2、示例
MyStack* obj = new MyStack();
* obj->push(1);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
3、題解
基本思想:隊列,用隊列實現棧
當隊列push新進來一個元素val,則將隊列裏原來的所有元素依次出隊列重新依次入隊列,這樣就使得新元素val位於隊頭了而且原來元素順序不變,入棧時間複雜度O(N)出棧時間複雜度O(1)。
#include<iostream>
#include<algorithm>
#include<vector>
#include<deque>
using namespace std;
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
//基本思想:隊列,用隊列實現棧
//當隊列push新進來一個元素val,則將隊列裏原來的所有元素依次出隊列重新依次入隊列,這樣就使得新元素val位於隊頭了而且原來元素順序不變
//入棧時間複雜度O(N)出棧時間複雜度O(1)
}
/** Push element x onto stack. */
void push(int x) {
int len = queue.size();
queue.push_back(x);
while (len--)
{
int val = queue.front();
queue.pop_front();
queue.push_back(val);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int val = queue.front();
queue.pop_front();
return val;
}
/** Get the top element. */
int top() {
return queue.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return queue.empty();
}
private:
deque<int> queue;
};
int main()
{
MyStack obj;
obj.push(1);
obj.push(2);
cout << obj.pop() << endl;
cout << obj.top() << endl;
cout << obj.empty() << endl;
return 0;
}