用栈实现队列

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
package main

import "fmt"

type MyQueue struct {
inStack []int
outStack []int
}

func Constructor() MyQueue {
return MyQueue{}
}

func (q *MyQueue) Enqueue(x int) {
q.inStack = append(q.inStack, x)
}

func (q *MyQueue) Dequeue() int {
if len(q.outStack) == 0 {
q.transfer()
}

if len(q.outStack) == 0 {
// 队列为空,返回一个合适的默认值,或者根据实际情况决定如何处理
return 0
}

val := q.outStack[len(q.outStack)-1]
q.outStack = q.outStack[:len(q.outStack)-1]
return val
}

func (q *MyQueue) transfer() {
for len(q.inStack) > 0 {
q.outStack = append(q.outStack, q.inStack[len(q.inStack)-1])
q.inStack = q.inStack[:len(q.inStack)-1]
}
}

func main() {
queue := Constructor()

queue.Enqueue(1)
queue.Enqueue(2)
queue.Enqueue(3)

fmt.Println(queue.Dequeue()) // 输出:1
fmt.Println(queue.Dequeue()) // 输出:2

queue.Enqueue(4)

fmt.Println(queue.Dequeue()) // 输出:3
fmt.Println(queue.Dequeue()) // 输出:4
}