用接口实现堆栈

来源:互联网 发布:网络机柜图 编辑:程序博客网 时间:2024/06/02 05:15
//define an integer stack interface.interface IntStack{void push(int item); //store an itemint pop();}//An implementtation of IntStack that uses fixed storage.class FixedStack implements IntStack{private int stck();private int tos;//allocate and initialize stackFixedStack(int size){stck = new int[size];tos = -1;}//push an item onto the stackpublic void push(int item){if(tos == stck.length-1)  //use length memberSystem.out.println("Stack is full.");elsestck[++tos] = item;}//pop an item from the stackpublic int pop(){if(tos < 0){System.out.println("Stack underflow.");return 0;}elsereturn stck[tos--];}}class IFTest{public static void main(String args[]){FixedStack mystack1 = new FixedStack(5);FixedStack mystack2 = new FixedStack(8);//push some numbers onto the stackfor(int i=0; i<5; i++)  mystack1.push(i);for(int i=0; i<8; i++)  mystack2.push(i);//pop those numbers off the stackSystem.out.println("Stack in mystack1;");for(int i=0; i<5; i++)System.out.println("mystack1.pop()");System.out.println("Stack in mystak2:");for(int i=0; i<8; i++)System.out.println("mystack2.pop()");}}//IntStack另一个实现,使用相同的interface定义来创建一个动态堆栈//Implement a "growable" stackclass DynStack implements IntStack{private int stck[];private int tos;//allocate and initialize stackDynStack(int size){stck = new int[size];tos = -1;}//push an item onto the stackpublic void push(int item){//if stack is full, allocate a larger stackif(tos == stck.length-1){int temp[] = new int[stck.length * 2];for(int i=0; i<stck.length; i++)  temp[i] = stck[i];stck = temp;stck[++tos] = item;}elsestck[++tos] = item;}//pop an item from the stackpublic int pop(){if(tos < 0){System.out.println("Stack underflow.");return 0;}elsereturn stck[tos--];}}class IFTest2{public static void main(String args[]){DynStack mystack1 = new DynStack(5);DynStack mystack2 = new DynStack(8);//these loops cause each stack to growfor(int i=0; i<12; i++)  mystack1.push(i);for(int i=0; i<20; i++)  mystack2.push(i);System.out.println("Stack in mystack1:");for(int i=0; i<12; i++)System.out.println(mystack2.pop());System.out.println("Stack in mystack2:");for(int i=0; i<20; i++)System.out.println(mystack2.pop());}}

原创粉丝点击