Skip to content

Commit a5d87da

Browse files
committed
栈: 用队列实现栈
Change-Id: I8c377086696bf645ac82356d46bf139fe3141cf0
1 parent 1449af6 commit a5d87da

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

go/leetcode/225.用队列实现栈.go

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package leetcode
2+
3+
/*
4+
* @lc app=leetcode.cn id=225 lang=golang
5+
*
6+
* [225] 用队列实现栈
7+
*
8+
* https://leetcode-cn.com/problems/implement-stack-using-queues/description/
9+
*
10+
* algorithms
11+
* Easy (61.24%)
12+
* Likes: 89
13+
* Dislikes: 0
14+
* Total Accepted: 22.2K
15+
* Total Submissions: 36.3K
16+
* Testcase Example: '["MyStack","push","push","top","pop","empty"]\n[[],[1],[2],[],[],[]]'
17+
*
18+
* 使用队列实现栈的下列操作:
19+
*
20+
*
21+
* push(x) -- 元素 x 入栈
22+
* pop() -- 移除栈顶元素
23+
* top() -- 获取栈顶元素
24+
* empty() -- 返回栈是否为空
25+
*
26+
*
27+
* 注意:
28+
*
29+
*
30+
* 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty
31+
* 这些操作是合法的。
32+
* 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
33+
* 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
34+
*
35+
*
36+
*/
37+
38+
// @lc code=start
39+
import (
40+
"container/list"
41+
)
42+
43+
type MyStack struct {
44+
Data *list.List
45+
}
46+
47+
/** Initialize your data structure here. */
48+
func Constructor() MyStack {
49+
return MyStack{
50+
Data: list.New(),
51+
}
52+
}
53+
54+
/** Push element x onto stack. */
55+
func (this *MyStack) Push(x int) {
56+
this.Data.PushBack(x)
57+
}
58+
59+
/** Removes the element on top of the stack and returns that element. */
60+
func (this *MyStack) Pop() int {
61+
el := this.Data.Back()
62+
if el == nil {
63+
return 0
64+
}
65+
return this.Data.Remove(el).(int)
66+
}
67+
68+
/** Get the top element. */
69+
func (this *MyStack) Top() int {
70+
el := this.Data.Back()
71+
if el == nil {
72+
return 0
73+
}
74+
return el.Value.(int)
75+
}
76+
77+
/** Returns whether the stack is empty. */
78+
func (this *MyStack) Empty() bool {
79+
return this.Data.Len() <= 0
80+
}
81+
82+
/**
83+
* Your MyStack object will be instantiated and called as such:
84+
* obj := Constructor();
85+
* obj.Push(x);
86+
* param_2 := obj.Pop();
87+
* param_3 := obj.Top();
88+
* param_4 := obj.Empty();
89+
*/
90+
// @lc code=end

0 commit comments

Comments
 (0)