数据结构—栈(基于Java单链表实现栈push,pop)

数据结构—栈(基于Java单链表实现栈push,pop)


栈是一个先入后出(First in Last Out)的有序列表,栈底固定,栈顶(top)指向新放入的元素。创建一个栈需要先定义栈的最大容量 maxSize。每次放入新元素都创建一个新的 top,其 value为元素值, next为旧top。

class LinkedListStack{
    private LinkNode top;
    private int maxSize;
    public int elementNum;

    public LinkedListStack(int maxSize){
        top = null;
        this.maxSize = maxSize;
        this.elementNum = 0;
    }

    public void setTop(LinkNode top){
        this.top = top;
    }
    public boolean isFull(){
        return elementNum==maxSize;
    }
    public boolean isEmpty(){
        return elementNum==0;
    }

    public void push(int value){
        if (isFull()) {
            throw new RuntimeException("Stack is Full!");
        }
        setTop(new LinkNode(value,top));
        elementNum ++;
        return;
    }
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("Stack is Empty!");
        }
        elementNum --;
        int value = top.getNo();
        setTop(top.getNext());
        return value;
    }
    public void showStack(){
        if (elementNum==0){
            System.out.println("Stack is Empty!");
            return;
        }
        LinkNode temp = top;
        for (int i = 0; i < elementNum; i++) {
            System.out.printf("stack[%d] = %d\n",i,temp.getNo());
            temp = temp.getNext();
        }
        return;
    }
}

class LinkNode{
    private int no;
    private LinkNode next;
    public LinkNode(int no, LinkNode next){
        this.no = no;
        this.next = next;
    }
    public LinkNode(){
    }
    public LinkNode(int no){
        this.no = no;
        this.next = null;
    }
    public LinkNode(LinkNode node){
        this.next = node;
    }

    public int getNo() {
        return no;
    }
    public LinkNode getNext(){
        return next;
    }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值