[LeetCode] 232. Implement Queue using Stacks

Chobby·2025년 2월 21일
1

LeetCode

목록 보기
249/427

😎풀이

  1. stackqueue정의
  2. push가 입력될 경우 stack에 입력
  3. pop이 입력될 경우 queue에 요소가 있다면 그대로 pop 하되, 그렇지 않다면 stack의 요소를 그대로 pop하여 queue로 옮김. 해당 과정에서 요소는 후입 선출에서 선입 선출되는 방식으로 변경됨
  4. peek이 입력될 경우 queue에 요소가 있다면 그대로 peek 하되, 그렇지 않다면 stack의 요소를 그대로 pop하여 queue로 옮김. 해당 과정에서 요소는 후입 선출에서 선입 선출되는 방식으로 변경됨
  5. empty가 입력될 경우, stackqueue 모두 비어있는지 검사
class MyQueue {
    private stack: number[]
    private queue: number[]
    constructor() {
        this.stack = []
        this.queue = []
    }

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

    pop(): number {
        if(this.queue.length) return this.queue.pop()
        while(this.stack.length) this.queue.push(this.stack.pop())
        return this.queue.pop()
    }

    peek(): number {
        if(this.queue.length) return this.queue.at(-1)
        while(this.stack.length) this.queue.push(this.stack.pop())
        return this.queue.at(-1)
    }

    empty(): boolean {
        return !(this.stack.length || this.queue.length)
    }
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글