文章

LeetCode232 用栈实现队列

LeetCode232 用栈实现队列 使用栈实现队列的下列操作:

push(x) – 将一个元素放入队列的尾部。 pop() – 从队列首部移除元素。 peek() – 返回队列首部的元素。 empty() – 返回队列是否为空。

示例:

MyQueue queue = new MyQueue(); queue.push(1); queue.push(2);
queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false

思路和用队列实现栈一样,只需要注意 push 操作。 最后代码如下,提交到 LeetCode 一次成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class MyQueue {
public:
	/** Initialize your data structure here. */
	MyQueue() {

	}

	/** Push element x to the back of queue. */
	void push(int x) {
		stack<int> temp_s;
		while (!s.empty())
		{
			int num = s.top();
			s.pop();
			temp_s.push(num);
		}
		s.push(x);
		while (!temp_s.empty())
		{
			int num = temp_s.top();
			temp_s.pop();
			s.push(num);
		}
	}

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

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

	/** Returns whether the queue is empty. */
	bool empty() {
		return s.empty();
	}
private:
	stack<int> s;
};
本文由作者按照 CC BY 4.0 进行授权