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; } }