本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2024-11(1)

练习题:数组模拟栈数据结构

发布于2020-11-19 20:33     阅读(1238)     评论(0)     点赞(30)     收藏(5)


package com.javase.advanced.work02;

/*  1.栈可以存储java中任何引用类型的数据
    2.提供push方法压栈(栈满
    3.提供pop方法弹栈(栈空
    4.编写测试程序,new栈对象,调用push pop方法模拟压栈弹栈动作
    5.默认初始化容量是10(无参数

*/
public class Stack {
    //Object 父类 可以存储任何引用类型
    private Object[] elements;
    private int index;

    public Stack() {
        this.elements = new Object[10];
        this.index = -1;
    }

    public Object[] getElements() {
        return elements;
    }

    public void setElements(Object[] elements) {
        this.elements = elements;
    }

    public void push(Object o) {
        if (index >= elements.length - 1) {
            System.out.println("栈满,压栈失败");
            return;
        }
        /*思维?
        elements[index + 1] = o;
        index++;
         */
        elements[++index] = o;
        System.out.println("压栈" + o + "成功,栈帧指向" + index);

    }

    public void pop() {
        if (index < 0) {
            System.out.println("栈空,弹栈失败");
            return;
        }
        System.out.print("弹栈" + elements[index] + "元素成功,");
        elements[index--] = null;//思考?
        //index--;
        System.out.println("栈帧指向" + index);
    }

    public void traversal() {
        for (int i = 0; i <= elements.length - 1; i++) {
            System.out.print(elements[i] + "     ");
        }
        System.out.println();
    }
}
//还是开始没思路,读答案一半才写出来


```java
ackage com.javase.advanced.work02;

public class Test01 {
    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.pop();
        stack.pop();
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.pop();
        stack.pop();
        stack.traversal();
        //System.out.println(stack.getElements());
        // String[] array = {"1", "2", "3", "4", "7"};
        // stack.setElements(array);


    }
}

原文链接:https://blog.csdn.net/weixin_51891578/article/details/109784766



所属网站分类: 技术文章 > 博客

作者:java之恋

链接:http://www.javaheidong.com/blog/article/1034/d41ad88df232939e5e1a/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

30 0
收藏该文
已收藏

评论内容:(最多支持255个字符)