用数组和链表实现顺序栈和链式栈

基于数据的顺序栈

public class ArrayStack<T> {
    private T[] data;
    private int n;
    private int count;

    public ArrayStack(int n){
        this.data= (T[]) new Object[n];
        this.n=n;
        this.count=0;
    }

    //压入数据
    public boolean push(T value){
        if (this.count==this.n) throw new ArrayIndexOutOfBoundsException("数组满了");
        this.data[count++]=value;
        return true;
    }

    //弹出
    public T pop(){
        if (this.count==0) throw new NullPointerException("已经全部弹出");
        T data=this.data[--count];
        this.data[count]=null;//设置为null,jvm就会自动回收垃圾
        return data;
    }

    //判断是否为空数组
    public  boolean isEmpty(){
        if (this.count==0)
            return true;
        return false;
    }

    //打印所有数据
    private void printAll(){
        for (int i=0;i<this.count;i++){
            System.out.println(this.data[i]);
        }
    }

    public static void main(String[] args) {
        ArrayStack arrayStack=new ArrayStack(6);
        arrayStack.push(1);
        arrayStack.push(2);
        arrayStack.push(3);
        arrayStack.push(4);
        arrayStack.push(5);
        arrayStack.push(6);

        System.out.println("弹出"+ arrayStack.pop());
        System.out.println("弹出"+arrayStack.pop());

        arrayStack.printAll();
    }

}

输出结果

弹出6
弹出5
1
2
3
4

基于链表的链式栈

public class LinkedListStack<T> {
    private Node head;
    private int count;

    public LinkedListStack(){
        this.count=0;
    }
    
    //压入
    public boolean push(T value){
        if(this.head==null) {
            this.head=new Node(value,null);
        }
        else{
            Node newNode=new Node(value,null);
            newNode.next=this.head;
            this.head=newNode;
        }
        this.count++;
        return true;
    }

    //弹出
    public T pop(){
        if (this.count==0) throw new NullPointerException("没了");
        T data= (T) this.head.data;
        this.head=this.head.next;
        --count;
        return data;
    }

    //节点
    private class Node<T>{
        public T data;
        public Node next;

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

    //打印
    private void printAll(){
        Node p=this.head;
        while (p!=null){
            System.out.println(p.data);
            p=p.next;
        }
    }

    public static void main(String[] args) {
        LinkedListStack lstack=new LinkedListStack();
        lstack.push(1);
        lstack.push(2);
        lstack.push(3);

        lstack.pop();

        lstack.printAll();
    }
}

输出结果

弹出3
2
1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值