java實現棧的數據結構


棧是一種數據結構,只能從一端進行存儲和訪問。常規操作有壓入棧和彈出棧。 
特性:先進先出,LIFO 
以下是用ArrayList為內核實現一個棧的數據結構 

import java.util.ArrayList;
import java.util.List;
import java.util.EmptyStackException;

public class Statck<E extends Object> {
    private List<E> pool = new ArrayList<E>();

    public Statck() {
    }

    public void clear() {
        pool.clear();
    }

    public boolean isEmpty() {
        return pool.isEmpty();
    }

    /**
     * 獲取棧頂元素
     * */
    public E getTopObjcet() {
        if (isEmpty()) {return null;}
        return pool.get(pool.size()-1);
    }

    /**
     * 彈出棧操作
     * */
    public E pop() {
        if (isEmpty()) {throw new EmptyStackException();}
        return pool.remove(pool.size() - 1);
    }

    /**
     * 壓入棧
     * */
    public void push(E e) {
        if (isEmpty()) {throw new EmptyStackException();}
        pool.add(e);
    }

    /**
     * 獲取當前棧大小
     * */
    public int getStatckSize() {
        if (isEmpty()) {throw new EmptyStackException();}
        return pool.size();
    }

}

以鏈表方式實現一個棧 

public class Statck<E extends Object> {
    private List<E> pool = new ArrayList<E>();

    public Statck() {
    }

    public void clear() {
        pool.clear();
    }

    public boolean isEmpty() {
        return pool.isEmpty();
    }

    /**
     * 獲取棧頂元素
     * */
    public E getTopObjcet() {
        if (isEmpty()) {return null;}
        return pool.get(0);
    }

    /**
     * 彈出棧操作
     * */
    public E pop() {
        if (isEmpty()) {throw new EmptyStackException();}
        return pool.remove(pool.size() - 1);
    }

    /**
     * 壓入棧
     * */
    public void push(E e) {
        if (isEmpty()) {throw new EmptyStackException();}
        pool.add(e);
    }

    /**
     * 獲取當前棧大小
     * */
    public int getStatckSize() {
        if (isEmpty()) {throw new EmptyStackException();}
        return pool.size();
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM