-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path232.implement-queue-using-stacks.go
More file actions
75 lines (62 loc) · 1.66 KB
/
232.implement-queue-using-stacks.go
File metadata and controls
75 lines (62 loc) · 1.66 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
/*
* @lc app=leetcode id=232 lang=golang
*
* [232] Implement Queue using Stacks
*/
type MyQueue struct {
stack1 []int
stack2 []int
}
/** Initialize your data structure here. */
func Constructor() MyQueue {
return MyQueue{
stack1:make([]int,0),
stack2:make([]int,0),//必须有逗号
}
}
/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int) {
this.stack1 = append(this.stack1,x)
}
/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
// 题目要求,不需要考虑为空时的情况
if len(this.stack2) != 0{
top := this.stack2[len(this.stack2)-1]
this.stack2 = this.stack2[:len(this.stack2)-1]
return top
}
for len(this.stack1) != 0{
top := this.stack1[len(this.stack1)-1]
this.stack1 = this.stack1[:len(this.stack1)-1]
this.stack2 = append(this.stack2,top)
}
top := this.stack2[len(this.stack2)-1]
this.stack2 = this.stack2[:len(this.stack2)-1]
return top
}
/** Get the front element. */
func (this *MyQueue) Peek() int {
// 不用考虑为空时的情况
if len(this.stack2) != 0{
return this.stack2[len(this.stack2)-1]
}
for len(this.stack1) != 0{
top := this.stack1[len(this.stack1)-1]
this.stack1 = this.stack1[:len(this.stack1)-1]
this.stack2 = append(this.stack2,top)
}
return this.stack2[len(this.stack2)-1]
}
/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
return len(this.stack1) == 0 && len(this.stack2) == 0
}
/**
* Your MyQueue object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Peek();
* param_4 := obj.Empty();
*/