java数据结构与算法链表模拟栈(含完整Demo)

其他文章:

java数组模拟栈

java栈的使用

什么是栈上面2篇文章说很多次了,一句话总结:栈遵循了先进后出的原则

添加元素

单链表增删改查

只需要移动到最后面,然后temp.next = heroNode;即可

image.png

弹出元素

使用链表弹出元素只需要弹出最后一个元素即可

image.png

弹出最后一个元素的时候,走到需要删除元素的前一个位置,然后temp.next = null即可

image.png

链表节点类

这个节点累没什么大难度,很普通的一个节点类

public class HeroNode4 {
    int id;
    String name;
    HeroNode4 next;

    public HeroNode4(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "HeroNode4{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
复制代码

完整代码:

public class StackLinkedList {

    private final HeroNode4 head = new HeroNode4(0, "");

    //添加元素
    public void push(HeroNode4 heroNode) {

        HeroNode4 temp = head;

        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = heroNode;
    }

    //弹出元素
    public void pop() {
        if (head.next == null) {
            throw new RuntimeException("pop:链表中没有数据,不能弹出");
        }

        HeroNode4 temp = head;

        while (temp.next.next != null) {
            temp = temp.next;
        }
        temp.next = null;
    }

    //输出所有元素
    public void show() {
        if (head.next == null) {
            System.out.println("show:链表为null,不能打印");
            return;
        }

        HeroNode4 temp = head;

        Stack<HeroNode4> stack = new Stack<>();

        while (temp.next != null) {
            temp = temp.next;
            stack.push(temp);
        }

        //判断栈中是否为空,不为空就一直弹出
        while (!stack.empty()) {
            System.out.println("show:" + stack.pop());
        }
    }
}
复制代码

测试代码:

public static void main(String[] args) {
        StackLinkedList stackLinkedList = new StackLinkedList();

        //添加元素
        stackLinkedList.push(new HeroNode4(1, "宋江"));
        stackLinkedList.push(new HeroNode4(2, "黄飞鸿"));
        stackLinkedList.push(new HeroNode4(3, "李逵"));
        stackLinkedList.push(new HeroNode4(4, "查理"));

        try {
            //弹出元素
            stackLinkedList.pop();
            stackLinkedList.pop();
//            stackLinkedList.pop();
//            stackLinkedList.pop();
//            stackLinkedList.pop();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        stackLinkedList.show();
    }
复制代码

运行结果为:

show:HeroNode4{id=2, name='黄飞鸿'}
show:HeroNode4{id=1, name='宋江'}
复制代码

完整代码

完整代码

猜你喜欢:

java数据结构与算法目录

原创不易,您的点赞就是对我最大的支持!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享