이진 트리의 재건
시간 제한 : 1秒
공간 제약 : 32768K
이 질문 지식 : 队列
栈
제목 설명 :
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
}
public int pop() {
}
}
아이디어의 분석 :
순차적으로의 작동은 다음의 변화를 겪는다 :
두 스택이 비어 있습니다
-> stack1하지 빈 빈 stack2
-> stack1 빈 stack2 비어 있지
-> 두 스택이 비어 있지 않은
두 스택이 비어 있습니다
두 스택이 비어 있습니다 | stack1 = [] | stack2 = [] | 단계 |
---|---|---|---|
도면 {1, 2} | stack1 = [2,1] | stack2 = [] | 2 * stack1.push |
대중적인 | stack1 = [] | stack2 = [] | 는 null |
stack1하지 빈 stack2 빈에게
빈 1이 비어 있지 | stack1 = [2,1] | stack2 = [] | 단계 |
---|---|---|---|
도면 {3,4} | stack1 = 4, 3, 2, 1] | stack2 = [] | 2 * stack1.push |
대중적인 | stack1 = [] | stack2 = 2, 3, 4] | 4 * stack1.pop 4 * stack2.push의 반환 stack2.pop을 |
stack1 빈 stack2 비어 있지
빈 1이 비어 있지 | stack1 = [] | stack2 = 2, 3, 4] | 단계 |
---|---|---|---|
도면 {5,6} | stack1 = [5,6] | stack2 = 2, 3, 4] | 2 * stack1.push |
대중적인 | stack1 = [] | stack2 = [3,4] | stack2.pop 반환 |
두 스택이 비어 있지
두 스택이 비어 있지 | stack1 = [5,6] | stack2 = 2, 3, 4] | 단계 |
---|---|---|---|
그리기 {7, 8} | stack1 = 8, 7, 6, 5] | stack2 = 2, 3, 4] | 2 * stack1.push |
대중적인 | stack1 = [5,6] | stack2 = [3,4] | stack2.pop 반환 |
요약 :
- 상황을 스택 : 항상 stack1.push
- 스택의 경우 :
- 빈 stack2 : stack2에 스택 stack1의 모든 요소, 다음 stack2.pop을 수행
- stack2 비어 있지 : stack2.pop
답변 :
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
// 若 stack2 为空:将所有 stack1 元素入栈到 stack2
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}