- 用兩個(gè)棧來實(shí)現(xiàn)一個(gè)隊(duì)列摔敛,完成隊(duì)列的Push和Pop操作。 隊(duì)列中的元素為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() {
}
}
- 思路:push操作直接壓入棧stack1惹想,pop操作借助stack2盼产,取出最先入棧的元素,再重構(gòu)stack1
- 代碼:
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() {
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int first=stack2.pop();
while (!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return first;
}