数据结构之栈java实现

STACK ADT

栈是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,栈的顶。

对栈的基本操作有进战和出栈。栈有一个特性是先进后出。

由于栈是表的一种方式,所以任意实现表的方法都可以实现栈。

栈的链表实现

使用单链表,在表的顶端进行插入删除。

public class MyStack<AnyType> {

    Node<AnyType> Bottom,beBottom;
    int length;

    public MyStack(){
        doClear();
    }
    public void clear(){doClear();}

    public void doClear(){
        Bottom=new Node<>(null,null);                //初始化栈底
        length=0;
    }
    public int size(){return length;}
    public Node<AnyType> getNode(int idx){         //根据位置获得节点,但一般都是栈顶
        Node<AnyType> node=Bottom;
        for (int i = 0; i < idx; i++)
            node= node.behind;
        return node;
    }

    public void put(AnyType data){put(size(),data);}  //给用户提供 栈顶放入元素
    public void put(int idx,AnyType data){putBehind(getNode(idx),data);}
    public void putBehind(Node<AnyType> node,AnyType data){
        Node<AnyType> newN=new Node<>(null,data);
        node.behind=newN;
        length++;
    }

   public AnyType push(){return push(size()-1);}//弹出栈顶元素
    private AnyType push(int idx) {
        if(idx<0)
            throw new IndexOutOfBoundsException();
        return pushTop(getNode(idx));
    }//获得栈顶下一个元素



    private AnyType pushTop(Node<AnyType> node) {
        Node<AnyType> newN=node.behind;
        node.behind=null;
        length--;
        return newN.data;
    }

    private static class Node<AnyType>{
        AnyType data;
        Node<AnyType> behind;
        public Node(Node<AnyType> behind,AnyType data){
            this.data=data;
            this.behind=behind;
        }
    }

测试

public class Test {
    public static void main(String[] args) {
        MyStack<Integer> list1=new MyStack<>();
        list1.put(1);
        list1.put(2);
        list1.put(3);
        while (list1.size()!=0)
            System.out.println(""+list1.push());
    }
}

数组实现

第二种方法是数组实现,比较简单 不做提供。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

TanGBx

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

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

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

打赏作者

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

抵扣说明:

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

余额充值