代码随想录算法训练营第十天 | 232. 用栈实现队列、225. 用队列实现栈

58 阅读1分钟

232. 用栈实现队列

使用两个栈分别作为输入栈和输出栈,输出栈的顺序正好和输入栈是相反的,push的时候直接向输入栈push,pop的时候,如果输出栈不为空直接pop就行,如果输出栈为空,把输入栈全部pop然后再push到输出栈,然后输出栈pop就行

class MyQueue {
  stackIn: MyStack
  stackOut: MyStack
  constructor() {
    this.stackIn = new MyStack()
    this.stackOut = new MyStack()
  }

  push(x: number): void {
    this.stackIn.push(x)
  }

  pop(): number {
    if (!this.stackOut.empty()) {
      return this.stackOut.pop()
    }
    while (!this.stackIn.empty()) {
      this.stackOut.push(this.stackIn.pop())
    }
    return this.stackOut.pop()
  }

  peek(): number {
    const x = this.pop()
    this.stackOut.push(x)
    return x
  }

  empty(): boolean {
    return this.stackIn.empty() && this.stackOut.empty()
  }
}

class MyStack {
  stack: number[]
  constructor() {
    this.stack = []
  }

  push(x: number) {
    this.stack.push(x)
  }

  pop(): number {
    return this.stack.pop()
  }

  clear() {
    this.stack = []
  }

  empty() {
    return !this.stack.length
  }
}

225. 用队列实现栈

使用一个队列,在pop的时候,把队列全部出队,然后把除了最后一个元素其它元素全部入队,返回刚才的最后一个元素即可

class MyStack {
  queue: MyQueue
  constructor() {
    this.queue = new MyQueue()
  }

  push(x: number): void {
    this.queue.push(x)
  }

  pop(): number {
    let n = null
    const len = this.queue.len()
    for (let i = 0; i < len; i++) {
      const x = this.queue.pop()
      if (i === len - 1) {
        n = x
      } else {
        this.queue.push(x)
      }
    }
    return n
  }

  top(): number {
    const n = this.pop()
    this.queue.push(n)
    return n
  }

  empty(): boolean {
    return this.queue.empty()
  }
}
class MyQueue {
  private queue: number[]
  constructor() {
    this.queue = []
  }

  push(x: number): void {
    this.queue.push(x)
  }

  pop(): number {
    return this.queue.shift()
  }

  empty(): boolean {
    return !this.queue.length
  }

  len(): number {
    return this.queue.length
  }
}