
😎풀이
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)
}
}