225用队列实现栈(队列)

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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章