欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-25 18:45:03
...

基于数据的顺序栈

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