Skip to content

Latest commit

 

History

History
68 lines (53 loc) · 1.29 KB

232.md

File metadata and controls

68 lines (53 loc) · 1.29 KB

用栈实现队列

解法一

type MyQueue struct {
in  []int
out []int
}


/** Initialize your data structure here. */
func Constructor() MyQueue {
    return MyQueue{
        in:make([]int,0,0),
        out:make([]int,0,0),
    }
}


/** Push element x to the back of queue. */
func (m *MyQueue) Push(x int)  {
    m.in = append(m.in,x)
}


/** Removes the element from in front of queue and returns that element. */
func (m *MyQueue) Pop() int {
    value := m.Peek()
    m.out = m.out[:len(m.out)-1]
    return value
}


/** Get the front element. */
func (m *MyQueue) Peek() int {
    if len(m.out)<=0 {
        for len(m.in) >0 {
            value := m.in[len(m.in)-1]
            m.out = append(m.out,value)
            m.in = m.in[:len(m.in)-1]
        }
    }
    return m.out[len(m.out)-1]
}



/** Returns whether the queue is empty. */
func (m *MyQueue) Empty() bool {
    if len(m.in)  == 0 && len(m.out) == 0{
        return true
    }
    return false
}


/**
 * Your MyQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Peek();
 * param_4 := obj.Empty();
 */

解法二

因为go里面并没有slice,所以说我们也可以使用go提供的list来代替我们在解法一中使用的slice的方式