제목 설명:
두 개의 대기열 만 사용하여 LIFO (후입 선출) 스택을 구현합니다. 구현 된 스택은 일반 대기열의 모든 기능 (push, top, pop 및 empty)을 지원해야합니다.
MyStack 클래스를 구현합니다.
- void push (int x) 요소 x를 스택의 맨 위로 푸시합니다.
- int pop () 스택 맨 위에있는 요소를 제거하고 반환합니다.
- int top () 스택 맨 위에있는 요소를 반환합니다.
- boolean empty () 스택이 비어 있으면 true를 반환하고 그렇지 않으면 false를 반환합니다.
노트:
- 큐의 표준 작업 만 사용해야합니다. 즉, 푸시 투 백, 앞쪽에서 픽 / 팝, 크기 및 빈 작업 만 유효합니다.
- 언어에 따라 대기열이 기본적으로 지원되지 않을 수 있습니다. 대기열의 표준 작업 만 사용하는 한 목록 또는 deque (양방향 대기열)를 사용하여 대기열을 시뮬레이션 할 수 있습니다.
예 1 :
입력
[ "MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
출력
[null , null, null, 2, 2, false]
설명
MyStack myStack = new MyStack ();
myStack.push (1);
myStack.push (2);
myStack.top (); // 반환 2
myStack.pop (); // 반환 2
myStack.empty (); // False 반환
제약 :
1 <= x <= 9
push, pop, top 및 empty에 대해 최대 100 개의 호출이 작성됩니다.
pop 및 top에 대한 모든 호출이 유효합니다.
시간 복잡성 : 푸시 O (n) 팝 O (1)
하나의 대기열
class MyStack {
Queue<Integer> q1;
/** Initialize your data structure here. */
public MyStack() {
q1 = new ArrayDeque<>();
}
/** Push element x onto stack. */
public void push(int x) {
q1.add(x);
int size = q1.size();
while (size > 1) {
q1.add(q1.remove());
size--;
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.remove();
}
/** Get the top element. */
public int top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/