stack演示

类似于往手枪里压入子弹,先进后出。

数组实现

package com.example.data;

/**
 * *@ClassName stack
 * *@Author yyc
 * *@Date 2020/6/15 13:46
 * 使用数组来实现堆栈结构
 **/
public class stackClass {
    private int length;

    //记录当前位置
    private int topIndex;
    private int[] stacklist;
    //设置堆栈的长度
    public void setSize(int len){
        this.length=len;
        stacklist=new int[len];
        topIndex=0;
    }

    //压入数据
    public void push(int v) throws Exception {
        if(topIndex<=length)
        {
            stacklist[topIndex++]=v;
        }
        else
        {
            throw  new Exception("空间已满");
        }
    }
    //弹出数据
    public int pop() throws Exception {
        if(topIndex>0)
        {
            return stacklist[--topIndex];
        }
        else
            throw new Exception(("已没有数据"));
    }

}

在这里插入图片描述

链表

package com.example.data;

import java.util.Iterator;

/**
 * *@ClassName Stack
 * *@Author yyc
 * *@Date 2020/6/15 14:08
 **/
public class Stack{

    public Node head;

    private int length;

    public Stack(){
        this.head=new Node(null,null);
        this.length=0;
    }

    public void push(Integer value)
    {
        Node oldNext=head.next;
        if(oldNext==null)
        {
            head.next=new Node(value,null);
        }
        else
            head.next=new Node(value,oldNext);
    }

    public Integer pop(){
        Node oldNext=head.next;
        if(oldNext!=null)
        {
            head.next=head.next.next;
            return (Integer) oldNext.item;
        }
        else
            return null;
    }
}


package com.example.data;

/**
 * *@ClassName Node
 * *@Author yyc
 * *@Date 2020/6/15 14:23
 **/
public class Node<T> {

    public T item;

    public Node next;

    public Node(T item,Node next){
        this.item=item;
        this.next=next;
    }
}

package com.example.data;

/**
 * *@ClassName Node
 * *@Author yyc
 * *@Date 2020/6/15 14:23
 **/
public class Node<T> {

    public T item;

    public Node next;

    public Node(T item,Node next){
        this.item=item;
        this.next=next;
    }
}


在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值