1. 程式人生 > >Java 實現棧,佇列

Java 實現棧,佇列

package base.structure;

/**
 * @program: Algorithm4J
 * @description: 實現一個Stack
 * @author: Mr.Dai
 * @create: 2018-12-06 15:25
 **/
public class Stack<T> {

    // point
    int n;
    // arrays implement
    T [] elements;

    // 初始化一個棧
    public   Stack(){
        n=0;
        elements
= ((T[]) new Object[20]); } public void push(T item){ if(n==elements.length){ resize(elements.length*2); } elements[n++]=item; } // 調控陣列大小 private void resize(int i) { T[] arrays=(T[])new Object[i]; System.arraycopy(elements,
0,arrays,0,elements.length); elements=arrays; } public T pop(){ if(isEmpty()) throw new ArrayIndexOutOfBoundsException(); T x=elements[n-1]; n--; return x; } public boolean isEmpty(){ return n==0; } public int Size(){return
n;} }

 佇列

 

package base.structure;

/**
 * @program: Algorithm4J
 * @description: 實現佇列
 * @author: Mr.Dai
 * @create: 2018-12-06 15:37
 **/
public class Queue<T> {

    // tail point
    private int tailp;
    // head point
    private int headp;
    // save arrays
    private T [] elements;

    public Queue(){
        tailp=0;
        elements=(T[])new Object[20];
    }

    // 入隊
    public void enqueue(T item){
        if(tailp==elements.length){
            resize(elements.length*2);
        }
        elements[tailp++]=item;
    }
    // 調控陣列大小
    private void resize(int i) {
        T[] arrays=(T[])new Object[i];
        System.arraycopy(elements,0,arrays,0,elements.length);
        elements=arrays;
    }
    // 出隊
    public T dequeue(){
        if (isEmpty()) throw new ArrayIndexOutOfBoundsException();
        T val=elements[headp];
        headp++;
        return val;
    }

    boolean isEmpty(){
        return headp==tailp;
    }

    public int Size(){
        return tailp-headp;
    }

}