Stack 栈认识

Stack 栈

***关于pop方法使用for循环输出少的原因***

​ 元素进出规则:FILO,先进后出

​ 继承Vector,扩充五个方法,分别是PUSH压入元素,POP弹出栈顶元素,PEEK查看堆栈顶部的对象,但不从堆栈中移除它。EMPTY测试堆栈是否为空,SEARCH返回对象在堆栈中的位置,以 1 为基数。

​ 注意:

​ POP每次执行一次,栈的大小减小1,如果使用for循环,当执行次数和栈的大小一致时,就不能继续弹出栈顶元素,如下所示

public class ss {
    
    
    public static void main(String[] args) {
    
    
        Stack<Chinchilla> stack = new Stack<>();
        for (int i = 0; i < 10; i++) {
    
    
            stack.push(new Chinchilla(""+i,"弟弟"));
        }
        System.out.println("出栈前的大小 "+stack.size());
        for (int i = 0; i < stack.size(); i++) {
    
    
            System.out.println(stack.pop());
        }

    }
}
运行结果:
出栈前的大小 10
龙猫{
    
    名称='9', 性别='弟弟'}
龙猫{
    
    名称='8', 性别='弟弟'}
龙猫{
    
    名称='7', 性别='弟弟'}
龙猫{
    
    名称='6', 性别='弟弟'}
龙猫{
    
    名称='5', 性别='弟弟'}

Process finished with exit code 0

我们可以看到,弹出第五只小龙猫时,就停止弹出栈顶元素,我们通过debug更容易看出来。
所有,要使用pop弹出栈顶所有元素,应当使用while循环,如下:

public class ss {
    
    
    public static void main(String[] args) {
    
    
        Stack<Chinchilla> stack = new Stack<>();
        for (int i = 0; i < 10; i++) {
    
    
            stack.push(new Chinchilla(""+i,"弟弟"));
        }
        System.out.println("出栈前的大小 "+stack.size());
       while (stack.size()!=0){
    
    
           System.out.println(stack.pop());
       }

    }
}
运行结果:
出栈前的大小 10
龙猫{
    
    名称='9', 性别='弟弟'}
龙猫{
    
    名称='8', 性别='弟弟'}
龙猫{
    
    名称='7', 性别='弟弟'}
龙猫{
    
    名称='6', 性别='弟弟'}
龙猫{
    
    名称='5', 性别='弟弟'}
龙猫{
    
    名称='4', 性别='弟弟'}
龙猫{
    
    名称='3', 性别='弟弟'}
龙猫{
    
    名称='2', 性别='弟弟'}
龙猫{
    
    名称='1', 性别='弟弟'}
龙猫{
    
    名称='0', 性别='弟弟'}

Process finished with exit code 0

或者,

public class ss {
    
    
    public static void main(String[] args) {
    
    
        Stack<Chinchilla> stack = new Stack<>();
        for (int i = 0; i < 10; i++) {
    
    
            stack.push(new Chinchilla(""+i,"弟弟"));
        }
        System.out.println("出栈前的大小 "+stack.size());
       while (!stack.empty()){
    
    
           System.out.println(stack.pop());
       }

    }
}
运行结果:
出栈前的大小 10
龙猫{
    
    名称='9', 性别='弟弟'}
龙猫{
    
    名称='8', 性别='弟弟'}
龙猫{
    
    名称='7', 性别='弟弟'}
龙猫{
    
    名称='6', 性别='弟弟'}
龙猫{
    
    名称='5', 性别='弟弟'}
龙猫{
    
    名称='4', 性别='弟弟'}
龙猫{
    
    名称='3', 性别='弟弟'}
龙猫{
    
    名称='2', 性别='弟弟'}
龙猫{
    
    名称='1', 性别='弟弟'}
龙猫{
    
    名称='0', 性别='弟弟'}

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/dddd2225/article/details/119189741