最多调用100 次 push、pop、top 和 empty 每次调用 pop 和 top 都保证栈不为空

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

//leetcode submit region begin(Prohibit modification and deletion)
type MyStack struct {
	stack []int
	n     int
}

func Constructor() MyStack {
	return MyStack{
		stack: []int{},
		n:     0,
	}
}

func (this *MyStack) Push(x int) {
	this.stack = append(this.stack, x)
	this.n ++
}

func (this *MyStack) Pop() int {
	l := len(this.stack)
	p := this.stack[l-1]
	this.stack = this.stack[:l-1]
	this.n --
	return p
}

func (this *MyStack) Top() int {
	return this.stack[len(this.stack) - 1]
}

func (this *MyStack) Empty() bool {
	return this.n == 0
}