Algorithm/PTUStudy

9주차. 스택,큐 (큐를 이용한 스택구현)

지구우중 2023. 3. 30. 18:57

21. 중복 문자 제거

https://leetcode.com/problems/implement-stack-using-queues/

 

Implement Stack using Queues - LeetCode

Can you solve this real interview question? Implement Stack using Queues - Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty). Implement the

leetcode.com

📌문제
큐를 이용해 다음 연산을 지원하는 스택을 구현하라

  • push(x): 요소x를 스택에 삽입한다.
  • pop(): 스택의 첫 번째 요소를 삭제한다.
  • top():스택의 첫 번째 요소를 가져온다.
  • empty(): 스택이 비어 있는지 여부를 리턴한다.


- 예제1
  📝입력

["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]



  💻출력

[null, null, null, 2, 2, false]

 

    
📌풀이

0ms, 40.2mb

class MyStack {
    private Queue<Integer> queue = new LinkedList<>();

    public MyStack() {
    
    }
    
    public void push(int x) {
        queue.add(x);
        for (int i=1; i<queue.size(); i++)
            queue.add(queue.poll());
    }
    
    public int pop() {
        return queue.poll();
    }
    
    public int top() {
        return queue.peek();
    }
    
    public boolean empty() {
        return queue.isEmpty();
    }
}