java用链表实现栈结构

首先看链表类

public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(){}
    public ListNode(int val){ this.val = val; }
    public ListNode(int val,ListNode next){this.val = val;this.next = next;}
    @Override
    public String toString() {
        return val + " -> " + next;
    }
}

栈:

public class ListNodeStack {
    ListNode head;//链表头节点
    int count;//栈内元素个数
    int size;//栈的大小
 
    public ListNodeStack() {//无参构造函数,初始化栈
        this.head = null;
        this.count = 0;
        this.size = 10;
    }
    public ListNodeStack(int size) {//构造函数指定栈大小
        head=null;
        count=0;
        this.size=size;
    }
    public boolean isFull(){//判断是否栈已满
        if(count==size){
            return true;
        }
        return false;
    }
    public boolean isEmpty(){//判断是否栈空
        if(count==0){
            return true;
        }
        return false;
    }
    public void push(int val){//压栈函数
        if(this.isFull()){
            throw new RuntimeException("stack is full");
        }
        ListNode l = new ListNode(val,head);
        head = l;
        count++;
    }
    public int pop(){//出栈函数
        if(this.isEmpty()){
            throw new RuntimeException("stack is empty");
        }
        int val = head.val;
        head = head.next;
        count--;
        return val;
    }
 
    public static void main(String[] args) {//测试一下
        int[] arr = {1,2,3,4,5,6,7};
        ListNodeStack stack = new ListNodeStack(10);
        for (int i = 0; i < arr.length; i++) {
            stack.push(arr[i]);
        }
        System.out.println(stack.pop());
 
    }
 
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值