본문으로 바로가기

Description

Stack 자료구조를 이용하여 선입선출(First In First Out) 구조의 Queue를 구현하는 문제입니다.

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

Notes:

  • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

Example 1:

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
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

Constraints:

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, peek, and empty.
  • All the calls to pop and peek are valid.

Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.

Solution 1.

public class MyQueue {

    private Stack<Integer> s1;
    private Stack<Integer> s2;
    public MyQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }

    public void push(int x) { // Stack의맨 아래로 들어가야

        while(!s1.isEmpty()){  // step1. 기존 스택의 데이터를 임시스택으로 옮김
            s2.push(s1.pop());
        }
        s1.push(x); //step2. 마지막 데이터를 가장 나중에 나갈 수 있게 제일 안쪽에 넣음

        while(!s2.isEmpty()){ // step3 다시 임시 스택에서 데이터를 가져옴
            s1.push(s2.pop());
        }

    }
    public int pop() {
        return s1.pop();
    }

    public int peek() {
        return s1.peek();
    }
    public boolean empty() {
        return s1.isEmpty();
    }
}

두개의 Stack을 이용하여 구현하는 방법입니다. push() 구현시 마지막 들어온 데이터가 스택의 가장 안쪽에 들어 갈 수 있도록 임시 스택(s2)로 기존 데이터를 모두 옮긴 뒤 넣어 주고 다시 쌓아주면 가장 먼저 들어온데이터가 가장 먼저 나갈 수 있게 됩니다.

FIFO로 데이터가 나갈 수 있게 순서를 조정했으므로 그 외 peek(), pop(), isEmpty는 그대로 구현해 주시면 됩니다.

Reference

 

Implement Queue using Stacks - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com