Leetcode Note :Go - Implement Stack using Queues

Implement Stack using Queues - LeetCode
https://leetcode.com/problems/implement-stack-using-queues/

  • Go 言語で取り組んだメモ

所感

  • Stack を実装する
  • ちょっと実践味というか、実際の実装感あってよい

回答

Implement Stack using Queues - LeetCode
https://leetcode.com/problems/implement-stack-using-queues/solution/

Golang 1 queue, pop O(n), push O(1) - LeetCode Discuss
https://leetcode.com/problems/implement-stack-using-queues/discuss/570763/Golang-1-queue-pop-O(n)-push-O(1)

type MyStack struct {
    Queue MyQueue
}


func Constructor() MyStack {
    return MyStack{
        Queue: MyQueue{[]int{}},
    }
}


func (this *MyStack) Push(x int)  {
    this.Queue.push(x)
}


func (this *MyStack) Pop() int {
    for i := 0; i < this.Queue.size() - 1; i++ {
        this.Queue.push(this.Queue.pop())
    }
    return this.Queue.pop()
}


func (this *MyStack) Top() int {
    for i := 0; i < this.Queue.size() - 1; i++ {
        this.Queue.push(this.Queue.pop())
    }

    x := this.Queue.pop()
    this.Queue.push(x)
    return x
}

func (this *MyStack) Empty() bool {
    return this.Queue.empty()
}

type MyQueue struct {
    Data []int
}

func (q *MyQueue) push(x int) {
    q.Data = append(q.Data, x)
}

func (q *MyQueue) pop() int {
    if len(q.Data) > 0 {
        x := q.Data[0]
        q.Data = q.Data[1:]
        return x
    }

    return 0
}

func (q *MyQueue) size() int {
    return len(q.Data)
}

func (q *MyQueue) empty() bool {
    return len(q.Data) == 0
}

/**
 * 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();
 */
  • MyQueue を定義して Stack を実装
    • データはスライスで管理して push や pop は append 使えば良い