NOTE

用两个栈实现队列

记录使用两个栈实现队列 Push、Pop、Peek 和 Empty 操作的方法。

Data Structures & Algorithms创建于 更新于 约 1 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

2. 思路

3. 实现

  • push操作就直接往stack1中push, pop操作需要分类一下:如果stack2为空,那么需要将stack1中的数据转移到stack2中,然后在对stack2进行pop,如果stack2不为空,直接pop就ok。
func stackPush(stack *[]int, data int) {
    *stack = append(*stack, data)
}

func stackPop(stack *[]int) int {
    if len(*stack) == 0 {return 0}
    data := (*stack)[len(*stack)-1]
    *stack = (*stack)[:len(*stack)-1]
    return data
}

func stackEmpty(stack *[]int) bool {
    return len(*stack) == 0
}

func stackPeek(stack *[]int) int {
    data := (*stack)[len(*stack)-1]
    return data
}

type MyQueue struct {
    pushStack []int
    popStack []int
}


func Constructor() MyQueue {
    return MyQueue{}
}


func (this *MyQueue) Push(x int)  {
    stackPush(&this.pushStack, x)
}


func (this *MyQueue) Pop() int {
    if stackEmpty(&this.popStack) {
        for !stackEmpty(&this.pushStack) {
            data := stackPop(&this.pushStack)
            stackPush(&this.popStack, data)
        }
    }
    if !stackEmpty(&this.popStack) {
        return stackPop(&this.popStack)
    }
    return 0
}


func (this *MyQueue) Peek() int {
    if stackEmpty(&this.popStack) {
        for !stackEmpty(&this.pushStack) {
            data := stackPop(&this.pushStack)
            stackPush(&this.popStack, data)
        }
    }
    if !stackEmpty(&this.popStack) {
        return stackPeek(&this.popStack)
    }
    return 0
}


func (this *MyQueue) Empty() bool {
    return stackEmpty(&this.popStack) && stackEmpty(&this.pushStack)
}


/**
 * 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();
 */

4. 参考

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看