|
1 | 1 | package main
|
2 | 2 |
|
3 |
| -// Runtime: 0 ms, faster than 100.00% of Go online submissions for Implement Stack using Queues. |
4 |
| -// Memory Usage: 1.9 MB, less than 82.31% of Go online submissions for Implement Stack using Queues. |
| 3 | +// // Runtime: 0 ms, faster than 100.00% of Go online submissions for Implement Stack using Queues. |
| 4 | +// // Memory Usage: 1.9 MB, less than 82.31% of Go online submissions for Implement Stack using Queues. |
| 5 | +// /* |
| 6 | +// type MyStack struct { |
| 7 | +// queue []int |
| 8 | +// } |
| 9 | + |
| 10 | +// /** Initialize your data structure here. */ |
| 11 | +// func Constructor() MyStack { |
| 12 | +// return MyStack{[]int{}} |
| 13 | +// } |
| 14 | + |
| 15 | +// /** Push element x onto stack. */ |
| 16 | +// func (this *MyStack) Push(x int) { |
| 17 | +// this.queue = append(this.queue[:0], append([]int{x}, this.queue[0:]...)...) // prepend |
| 18 | +// } |
| 19 | + |
| 20 | +// /** Removes the element on top of the stack and returns that element. */ |
| 21 | +// func (this *MyStack) Pop() int { |
| 22 | +// temp := this.queue[0] |
| 23 | +// this.queue = this.queue[1:] |
| 24 | +// return temp |
| 25 | +// } |
| 26 | + |
| 27 | +// /** Get the top element. */ |
| 28 | +// func (this *MyStack) Top() int { |
| 29 | +// return this.queue[0] |
| 30 | +// } |
| 31 | + |
| 32 | +// /** Returns whether the stack is empty. */ |
| 33 | +// func (this *MyStack) Empty() bool { |
| 34 | +// return len(this.queue) == 0 |
| 35 | +// } |
| 36 | + |
5 | 37 | type MyStack struct {
|
6 |
| - queue []int |
| 38 | + top int |
| 39 | + stack [100]int |
7 | 40 | }
|
8 | 41 |
|
9 |
| -/** Initialize your data structure here. */ |
10 | 42 | func Constructor() MyStack {
|
11 |
| - return MyStack{[]int{}} |
| 43 | + return MyStack{ |
| 44 | + top: -1, |
| 45 | + stack: [100]int{}, |
| 46 | + } |
12 | 47 | }
|
13 | 48 |
|
14 |
| -/** Push element x onto stack. */ |
15 | 49 | func (this *MyStack) Push(x int) {
|
16 |
| - this.queue = append(this.queue[:0], append([]int{x}, this.queue[0:]...)...) // prepend |
| 50 | + this.top++ |
| 51 | + this.stack[this.top] = x |
17 | 52 | }
|
18 | 53 |
|
19 |
| -/** Removes the element on top of the stack and returns that element. */ |
20 | 54 | func (this *MyStack) Pop() int {
|
21 |
| - temp := this.queue[0] |
22 |
| - this.queue = this.queue[1:] |
| 55 | + var temp int = this.stack[this.top] |
| 56 | + this.top-- |
23 | 57 | return temp
|
24 | 58 | }
|
25 | 59 |
|
26 |
| -/** Get the top element. */ |
27 | 60 | func (this *MyStack) Top() int {
|
28 |
| - return this.queue[0] |
| 61 | + return this.stack[this.top] |
29 | 62 | }
|
30 | 63 |
|
31 |
| -/** Returns whether the stack is empty. */ |
32 | 64 | func (this *MyStack) Empty() bool {
|
33 |
| - return len(this.queue) == 0 |
| 65 | + return this.top == -1 |
34 | 66 | }
|
0 commit comments