栈的操作练习(链表)


栈是一种先进后出(FILO)的有序列表,插入和删除元素只能在线性表的同一端进行操作,允许插入和删除的一端叫做栈顶(Top),另一端为固定的栈底(Bottom)
用链表来模拟栈,节点需要一个指向前一个节点的pre域和数据域

在这里插入图片描述

public class Node {
    private Node pre;
    private int no;

    public Node(int no) {
        this.no = no;
    }

    public Node getPre() {
        return pre;
    }

    public void setPre(Node pre) {
        this.pre = pre;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                '}';
    }
}

栈只需要一个栈顶即可

public class NodeStack {
    private Node top = null;
}

判断栈是否为空

判断栈为空的操作就是判断栈顶是否为null(前面初始化的栈顶就是为null)

    //判断是否为空
    public boolean isEmpty(){
        return top == null;
    }

入栈

在这里插入图片描述
链表入栈就是将入栈的节点pre域指向当前的栈顶,然后再将栈顶移到新压入栈中的节点

	//入栈
    public void push(Node node){
        node.setPre(top);
        top = node;
    }

出栈

在这里插入图片描述
出栈操作就是将当前栈顶记录下来,将top指向前一个节点,然后将记录下载的栈顶返回即可

    //出栈
    public Node pop(){
        if(isEmpty()){
            throw new RuntimeException("栈为空,无法出栈");
        }
        Node value = top;
        top = top.getPre();
        return value;
    }

遍历

栈的遍历是从栈顶开始向栈底进行遍历的

    //遍历
    public void list(){
        if(isEmpty()){
            System.out.println("栈为空,遍历失败");
            return;
        }
        Node temp = top;
        while(temp != null){
            System.out.println(temp);
            temp = temp.getPre();
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ht巷子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值