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

Jave栈实现

程序员文章站 2022-03-11 18:37:46
...

一.数组实现

public class ArrayStatck<T> {
    private final Object[] mElementArray;
    private  int initCapacity = 8;
    private int top = -1;

    ArrayStatck() {
        mElementArray = new Object[initCapacity];
    }

    public void push(T data) throws  Exception {
        if (top == mElementArray.length - 1) {
            throw new Exception("Stack is full!");
        }
        mElementArray[++top] = data;

    }

    public  Object pop() throws  Exception{
        if (top == -1) {
            throw new Exception("Stack is Empty");
        }
        return  mElementArray[top--];
    }

    public void display() {
        for (int i = 0; i <= top; i++) {
            System.out.println(mElementArray[i]);
        }
    }


}

二 链表实现

public class LinkStatck<T> {

    private LinkNode head;

    class LinkNode{
        T data;
        LinkNode next = null;

        public LinkNode(T data) {
            this.data = data;
        }
    }


    public void push(T data) {
        LinkNode linkNode = new LinkNode(data);
        if (head == null) {
            head = linkNode;
        }else {
            linkNode.next = head;
            head = linkNode;

        }
    }

    public T pop() {
        if (head == null) {
            return null;
        }
        T data = head.data;
        head = head.next;
        return data;

    }

    public void display() {
        if (head == null) {
            System.out.println("Statck is empty");
        }
        LinkNode curr = head;
        System.out.println(curr.data );
        while (curr.next != null) {
            curr = curr.next;
            System.out.println(curr.data );
        }

    }


}

 

相关标签: 技术点