使用单链表 模拟栈

//使用单链表模拟栈
class MM{
    public static void main(String[] args){
        singleList list=new singleList(5);
        list.push(1);
        list.push(2);
        list.push(3);
        list.push(4);
        list.showlist();
        list.pop();
        System.out.println("..............");
        list.showlist();
    }
}
class singleList{
    Node head=new Node(0);
    int maxSize;
    public singleList(int maxSize) {
        this.maxSize = maxSize;
    }
    void push(int n){
        Node temp=head;
        int i=0;
        while (true){
            if(temp.getNext()==null)break;
            temp=temp.getNext();
            i++;
        }
        if(i<maxSize){
        Node newnode=new Node(n);
        temp.setNext(newnode);
        }else{
            System.out.println("栈满!无法添加");
        }
    }
    void pop(){
        Node temp=head;
        if(temp.getNext()==null){
            System.out.println("栈空,无法抛出");
            return;
        }
        while (true){
            if(temp.getNext().getNext()==null)break;
            temp=temp.getNext();
        }
        temp.setNext(null);
    }
    void showlist(){
        Node temp=head.getNext();
        if(temp==null){
            System.out.println("栈空没有数据");
            return;
        }
        while (true){
            System.out.println(temp);
            temp=temp.getNext();
            if(temp==null)break;
        }

    }
}
class Node{
    private int no;
    private Node next;

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

    public int getNo() {
        return no;
    }

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

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                '}';
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值