Skip to content

Latest commit

 

History

History
43 lines (35 loc) · 867 Bytes

09. 用两个栈实现队列.md

File metadata and controls

43 lines (35 loc) · 867 Bytes

解题思路

两个栈,一个栈接收 in,一个栈作为输出

当插入,进 in 栈 当删除,删 out 栈,如果 out 栈为空,将 in 栈当前全部元素出栈再入栈 out 栈,再删 out 栈

// 尾部是栈顶
// in 入栈
// out 当 out 为空,从 in 出栈后入栈 out
type CQueue struct {
    in []int
    out []int
}

func Constructor() CQueue {
    return CQueue{}
}

func (t *CQueue) AppendTail(v int)  {
    t.in = append(t.in, v)
}

func (t *CQueue) DeleteHead() int {
    if len(t.in) == 0 && len(t.out) == 0 {
        return -1
    }
    if len(t.out) == 0 {
        for len(t.in) != 0 {
            t.out = append(t.out, t.in[len(t.in)-1])
            t.in = t.in[:len(t.in)-1]
        }
    }
    top := t.out[len(t.out)-1]
    t.out = t.out[:len(t.out)-1]
    return top
}