数组模拟栈

来源:互联网 发布:哈希算法 编辑:程序博客网 时间:2024/06/01 08:52
import java.lang.ref.SoftReference;/** * 使用数组模拟Java Stack类 * 1.压入一个元素void push() * 2.查看一个元素E peek() * 3.弹出一个元素E pop() * 4.获得元素个数int size() * 5.清空栈void clear() * **/class StackDemo<E>{private int SIZE;private int LENGTH;private Object[] o;public StackDemo(){this.SIZE=0;this.LENGTH=1;o=new Object[1];}public void push(E e){this.o[this.SIZE++]=e;if(this.SIZE==this.LENGTH)this.copy();}public E pop(){if(this.SIZE==0)throw new ArrayIndexOutOfBoundsException();E temp=(E)this.o[--this.SIZE];this.o[this.SIZE]=null;return temp;}public E peek(){if(this.SIZE==0)throw new ArrayIndexOutOfBoundsException();return (E)this.o[this.SIZE-1];}public int size(){return this.SIZE;}public void clear(){this.SIZE=0;this.LENGTH=1;this.o=new Object[1];}private void copy(){Object[] temp=new Object[this.LENGTH*2];SoftReference<Object[]> sr=new SoftReference<Object[]>(temp);for(int i=0;i<this.SIZE;i++)temp[i]=this.o[i];this.o=temp;temp=null;this.LENGTH*=2;}public String toString(){StringBuilder sb=new StringBuilder();SoftReference<StringBuilder> sr=new SoftReference<StringBuilder>(sb);sb.append("[");for(int i=0;i<this.SIZE-1;i++)sb.append(this.o[i]+",");if(this.SIZE!=0)sb.append(this.o[this.SIZE-1]);sb.append("]");String str=sb.toString();sb=null;return str;}}//测试用码public class StackTest {public static void main(String[] args){StackDemo<String> sk=new StackDemo<String>();System.out.println(sk);sk.push("kkkk");sk.push("llll");sk.push("ssss");sk.push("oooo");System.out.println(sk);System.out.println(sk.pop()+"::"+sk.pop()+"::"+sk.peek());sk.clear();System.out.println(sk);sk.push("pppp");System.out.println(sk);}}

0 0
原创粉丝点击