
😎풀이
stack
과 queue
정의
push
가 입력될 경우 stack
에 입력
pop
이 입력될 경우 queue
에 요소가 있다면 그대로 pop
하되, 그렇지 않다면 stack
의 요소를 그대로 pop
하여 queue
로 옮김. 해당 과정에서 요소는 후입 선출에서 선입 선출되는 방식으로 변경됨
peek
이 입력될 경우 queue
에 요소가 있다면 그대로 peek
하되, 그렇지 않다면 stack
의 요소를 그대로 pop
하여 queue
로 옮김. 해당 과정에서 요소는 후입 선출에서 선입 선출되는 방식으로 변경됨
empty
가 입력될 경우, stack
과 queue
모두 비어있는지 검사
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)
}
}