用栈实现队列
LeetCode232. 用栈实现队列
题目描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x
推到队列的末尾
int pop()
从队列的开头移除并返回元素
int peek()
返回队列开头的元素
boolean empty()
如果队列为空,返回 true
;否则,返回 false
说明:
你只能使用标准的栈操作 —— 也就是只有 push to top
, peek/pop from top
, size
, 和 is empty
操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list
或者 deque
(双端队列)来模拟一个栈,只要是标准的栈操作即可。
提示:
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop
或者 peek
操作)
示例 1:
1
2
3
4
5
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
1
2
3
4
5
6
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
思路
题目要求
用两个栈实现队列,且该队列类具有四个方法,分别是入队、出队、返回队头、判断队空
队列是先进先出,栈是先进后出。可以使用两个栈,一个输入栈,一个输出栈。
入队就是向输入栈压入元素;出队就是从输出栈弹出元素;队头即输出栈栈顶元素;输出栈和输入栈都为空即队空。
注意
出队:若输出栈非空,则直接弹出栈顶元素;若输出栈为空,则将输入栈全部元素 移入输出栈,然后弹出栈顶元素。
在Go语言中用切片模拟栈和队列
代码
Go
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// MyQueue 队列类
type MyQueue struct {
stackIn [] int
stackOut [] int
}
// Constructor 队列类的构造方法
func Constructor () MyQueue {
stackIn := make ([] int , 0 )
stackOut := make ([] int , 0 )
return MyQueue { stackIn , stackOut }
}
// Push 入队
func ( this * MyQueue ) Push ( x int ) {
// 向输入栈添加元素
this . stackIn = append ( this . stackIn , x )
}
// Pop 出队
func ( this * MyQueue ) Pop () int {
result := 0
// 输出栈为空,将输入栈全部元素移到输出栈
if len ( this . stackOut ) == 0 {
for len ( this . stackIn ) != 0 {
// 取出输入栈栈顶元素
temp := this . stackIn [ len ( this . stackIn ) - 1 ]
this . stackIn = this . stackIn [: len ( this . stackIn ) - 1 ]
// 将从输入栈取出的元素放入输出栈
this . stackOut = append ( this . stackOut , temp )
}
}
// 取出输出栈栈顶元素
result = this . stackOut [ len ( this . stackOut ) - 1 ]
this . stackOut = this . stackOut [: len ( this . stackOut ) - 1 ]
return result
}
// Peek 返回队列头元素
func ( this * MyQueue ) Peek () int {
result := 0
// 输出栈为空,将输入栈全部元素移到输出栈
if len ( this . stackOut ) == 0 {
for len ( this . stackIn ) != 0 {
// 取出输入栈栈顶元素
temp := this . stackIn [ len ( this . stackIn ) - 1 ]
this . stackIn = this . stackIn [: len ( this . stackIn ) - 1 ]
// 将从输入栈取出的元素放入输出栈
this . stackOut = append ( this . stackOut , temp )
}
}
// 得到输出栈栈顶元素
result = this . stackOut [ len ( this . stackOut ) - 1 ]
return result
}
// Empty 判断队空
func ( this * MyQueue ) Empty () bool {
if len ( this . stackIn ) == 0 && len ( this . stackOut ) == 0 {
return true
}
return false
}
Link
GitHub
最后更新于 Mar 20, 2022 20:08 UTC