LeetCode-Implement_Queue_using_Stacks

题目:

Implement the following operations of a queue using stacks.

  • 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.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).


翻译:

使用栈实现以下队列的操作。


  • push(x) -- 将元素 x 压入队列。
  • pop() -- 从队列头移除元素。
  • peek() -- 获得第一个元素。
  • empty() -- 返回队列是否为空。

注意:

  • 你需要使用标准的栈操作--就是说只有push to toppeek/pop from topsize和 is empty 操作是有效的。
  • 依赖于你使用的语言,栈可能不会被支持。 只要您只使用栈的标准操作,你可以使用列表或双端队列(双端队列)来模拟栈。
  • 你可以假设所有操作都是有效的(举例,没有pop或peek操作在空的队列中调用)。


思路:

使用两个栈来模拟队列,格外注意 push 操作,直接见代码。


C++代码(Visual Studio 2017):

class MyQueue {
public:
	/** Initialize your data structure here. */
	stack<int> s1;
	stack<int> s2;
	int front;
	/** Push element x to the back of queue. */
	void push(int x) {
		if (s1.empty())
			front = x;  //Please pay more attention here, It's 'front = x;' .
		while (!s1.empty()) {
			s2.push(s1.top());
			s1.pop();
		}
		s2.push(x);
		while (!s2.empty()) {
			s1.push(s2.top());
			s2.pop();
		}
	}

	/** Removes the element from in front of queue and returns that element. */
	int pop() {
		int n = s1.top();
		s1.pop();
		return n;

	}

	/** Get the front element. */
	int peek() {
		return s1.top();
	}

	/** Returns whether the queue is empty. */
	bool empty() {
		return s1.empty();
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值