题目:用两个栈来实现一个队列,完成队列的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) { stack1.push(node); } public int pop() { if (stack2.size() <= 0) { while (stack1.size() != 0) { stack2.push(stack1.pop()); } } return stack2.pop(); }
}
我的解答:(写繁琐了,问题出在每次进出不是必须要交换两个栈的数据的,贴上以示警告)
public class Q_5 {
Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); boolean isUse=false; public void push(int node) { while(isUse){ System.out.println("using"); } isUse=true; if(!stack2.isEmpty()){ stack1.empty(); while (!stack2.isEmpty()){ stack1.push(stack2.pop()); } } stack1.push(node); isUse=false; } public int pop() { while(isUse){ System.out.println("using"); } isUse=true; if(!stack1.isEmpty()){ stack2.empty(); while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } int result=stack2.pop(); isUse=false; return result; } public static void main(String[] args) { Q_5 test=new Q_5(); test.push(1); test.push(2); test.push(3); test.push(4); System.out.println(test.pop()); System.out.println(test.pop()); System.out.println(test.pop()); System.out.println(test.pop()); }
}