232. 用栈实现队列

leecode原题

题目

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

  • 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

示例

示例 1:

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

提示:

  • 1 <= x <= 9
  • 最多调用 100pushpoppeekempty
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek操作)

进阶

你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。

解题思路

思路

该题主要考察栈和队列的基本概念和基本功能函数。用栈实现队列,这里需要两个栈才行,一个输入栈,一个输出栈

具体思路:

  • push数据的时候,只要数据放进输入栈就好,但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了
  • 最后如何判断队列为空呢?如果进栈和出栈都为空的话,说明模拟的队列为空了。

实现

源码

type MyQueue struct {
    stackIn  []int // 输入栈
    stackOut []int // 输出栈
}

func Constructor() MyQueue {
    return MyQueue{
        stackIn:  make([]int, 0),
        stackOut: make([]int, 0),
    }
}

// 将元素 `x` 推到队列的末尾
func (this *MyQueue) Push(x int) {
    // 直接像输入栈塞入数据即可
    this.stackIn = append(this.stackIn, x)
    return
}

// 从队列的开头移除并返回元素
func (this *MyQueue) Pop() int {
    x := 0
    // 如果输出栈为空, 则将输入栈的数据读取存入输出栈(导入)
    if len(this.stackOut) == 0 && len(this.stackIn) != 0 {
        for i := len(this.stackIn) - 1; i >= 0; i-- {
            // 输入栈入栈
            this.stackOut = append(this.stackOut, this.stackIn[i])
        }
        this.stackIn = make([]int, 0)
    }
    // 从stackOut栈顶取元素
    if len(this.stackOut) > 0 {
        x = this.stackOut[len(this.stackOut)-1]
        this.stackOut = this.stackOut[:len(this.stackOut)-1]
    }
    return x
}

// 返回队列开头的元素
func (this *MyQueue) Peek() int {
    x := 0
    // 如果输出栈为空, 则将输入栈的数据读取存入输出栈(导入)
    if len(this.stackOut) == 0 && len(this.stackIn) != 0 {
        for i := len(this.stackIn) - 1; i >= 0; i-- {
            this.stackOut = append(this.stackOut, this.stackIn[i])
        }
        this.stackIn = make([]int, 0)
    }
    // 从stackOut栈顶取元素
    if len(this.stackOut) > 0 {
        x = this.stackOut[len(this.stackOut)-1]
    }
    return x
}

// 如果队列为空,返回 `true` ;否则,返回 `false`
func (this *MyQueue) Empty() bool {
    if len(this.stackIn) != 0 || len(this.stackOut) != 0 {
        return false
    }
    return true
}
Copyright © ROSEMARY666 2022 all right reserved,powered by Gitbook该文章修订时间: 2022-09-28 15:55:21

results matching ""

    No results matching ""