题目描述 : 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
首先分析一下基础知识:
①栈属于先进后出,如:进{1,2,3,4},出为{4,3,2,1}.
②队列属于先进先出,如:进{1,2,3,4},出为{1,2,3,4}.
那么用两个栈来实现一个队列,就相当于是负负得正.
然后栈stack的几种基础方法:
Ⅰ.进栈 stack.push()
Ⅱ.出栈 stack.pop()
Ⅲ.栈顶元素 stack.peek() 注:只显示并不会取出数据
Ⅳ.判空 stack.empty()
public class Test01 {
public static void main(String[] args) {
Stack stack=new Stack();
//1.empty()栈是否为空
System.out.println(stack.empty());
//2.peek()栈顶值
//3.进栈push()
stack.push(new Integer(1));
stack.push("b");
System.out.println(stack.peek());
//4.pop()出栈
stack.pop();
System.out.println(stack.peek());
}
}
输出结果为:
(1).true
(2).b
(3).1
理解了这几个方法,做题就简单了:
public class Solution {
//新创建栈(先进后出类)
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
//有数据存进来,放入栈1,然后再取出放进栈2,最后出栈
stack1.push(node);
}
public int pop() {
Integer num = null ;
//判断stack2是否为空
if(!stack2.empty()){
num = stack2.pop();
return num ;
}else{
while(!stack1.empty()){
num = stack1.pop();
stack2.push(num);
}
if(!stack2.empty()){
num = stack2.pop();
}
}
return num ;
}
}
顺便补充一点:Integer和Int的区别
①Integer是int的包装类,int则是java的一种基本数据类型
②Integer变量必须实例化后才能使用,而int变量不需要
③Integer实际是对象的引用,当new一个Integer时,实际上是生成一个指针指向此对象;而int则是直接存储数据值
④Integer的默认值是null,int的默认值是0
228




被折叠的 条评论
为什么被折叠?



