题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
时间限制:1秒 空间限制32768K
[问题分析]
package Offer;
import java.util.Stack;
class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int[] node) {
for(int i=node.length;i>0;i--){
stack1.push(node[i-1]);
System.out.print("进栈"+node[i-1]+" "); //数组中的元素进入栈1
}
}
public int pop() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop()); // 栈1中的元素进入栈2
}
int top=0;
top=stack2.pop();
// while(!stack2.isEmpty()) {
// stack1.push(stack2.pop());
// }
return top; //返回栈顶元素
}
}
public class Andpush {
public static void main(String[] args) {
Solution solution = new Solution();
int[] node = {1,2,3,4,5,6,7,8,9};
solution.push(node);
System.out.println("");
for(int i=0;i<node.length;i++){
System.out.print("出栈"+solution.pop()+" "); //栈2中的元素出栈 实现了队列的先进先出原则
}
}
}
代码中有三行是注释的,我不是很理解为什么要加这一句,在eclipse中没有这三行是可以通过的,而且我认为逻辑没有问题。
但是在线编程中如果没有这三行,也就是没有栈2入栈1,编译不通过,不是很明白。
package Offer;
import java.util.Stack;
class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int[] node) {
for(int i=node.length;i>0;i--){
stack1.push(node[i-1]);
System.out.print("进栈"+node[i-1]+" "); //数组中的元素进入栈1
}
}
public int pop() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop()); // 栈1中的元素进入栈2
}
int top=0;
top=stack2.pop();
// while(!stack2.isEmpty()) {
// stack1.push(stack2.pop());
// }
return top; //返回栈顶元素
}
}
public class Andpush {
public static void main(String[] args) {
Solution solution = new Solution();
int[] node = {1,2,3,4,5,6,7,8,9};
solution.push(node);
System.out.println("");
for(int i=0;i<node.length;i++){
System.out.print("出栈"+solution.pop()+" "); //栈2中的元素出栈 实现了队列的先进先出原则
}
}
}
代码中有三行是注释的,我不是很理解为什么要加这一句,在eclipse中没有这三行是可以通过的,而且我认为逻辑没有问题。
但是在线编程中如果没有这三行,也就是没有栈2入栈1,编译不通过,不是很明白。
结果
结果