123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- type MyStack struct {
- Peek Queue
- Body Queue
- }
- /** Initialize your data structure here. */
- func Constructor() MyStack {
- return MyStack{make([]int, 0), make([]int, 0)}
- }
- /** Push element x onto stack. */
- func (this *MyStack) Push(x int) {
- this.Peek.Enqueue(x)
- if this.Peek.Size() == 2 {
- this.Body.Enqueue(this.Peek.Dequeue())
- }
- }
- /** Removes the element on top of the stack and returns that element. */
- func (this *MyStack) Pop() int {
- n := this.Body.Size()
- top := this.Peek.Dequeue()
- for i := 0; i < n-1; i++ {
- this.Peek.Enqueue(this.Body.Dequeue())
- }
- this.Peek, this.Body = this.Body, this.Peek
- return top
- }
- /** Get the top element. */
- func (this *MyStack) Top() int {
- return this.Peek.Front()
- }
- /** Returns whether the stack is empty. */
- func (this *MyStack) Empty() bool {
- return this.Peek.Empty()
- }
- /**
- * Your MyStack object will be instantiated and called as such:
- * obj := Constructor();
- * obj.Push(x);
- * param_2 := obj.Pop();
- * param_3 := obj.Top();
- * param_4 := obj.Empty();
- */
- // Queue ...
- type Queue []int
- // Dequeue ...
- func (q *Queue) Dequeue() int {
- front := (*q)[0]
- *q = (*q)[1:]
- return front
- }
- // Enqueue ...
- func (q *Queue) Enqueue(x int) {
- *q = append(*q, x)
- }
- // Front ...
- func (q Queue) Front() int {
- return q[0]
- }
- // Size ...
- func (q Queue) Size() int {
- return len(q)
- }
- // Empty ...
- func (q Queue) Empty() bool {
- return len(q) == 0
- }
|