读书人

堆栈的简略模拟

发布时间: 2012-12-28 10:29:05 作者: rapoo

堆栈的简单模拟

public class Stack{
?int[] data;
?int maxSize;
?int top;
?
?/**初始化*/
?public Stack(int maxSize){
?? this.maxSize=maxSize;
?? data=new int[maxSize];
?? top=-1;
??}
??
?public boolean push(int data){
??if(top+1==maxSize){
???System.out.println("栈已满");
???}
???this.data[++top]=data;
???return true;
??}
??
??public int pop()throws Exception{
??
???if(top==-1){
????System.out.println("栈已空");
????}
????return this.data[top--];
???}
???
?public static void main(String[]args){
??? Stack s=new Stack(1000);
??? s.push(1);
??? s.push(2);
??? s.push(3);
??? s.push(4);
??? s.push(5);
??? s.push(6);
??? s.push(7);
?? try{
??? while(s.top>=0){
??? ?
??? ?System.out.println(s.pop());
??? ?}
?? }catch(Exception e){
?? ?? e.printStackTrace();
?? ?}
??}
}

读书人网 >编程

热点推荐