首页 > 代码库 > 顺序表代码

顺序表代码

 1 import java.util.*; 2 import java.lang.*; 3 import java.io.*; 4  5 /* Name of the class has to be "Main" only if the class is public. */ 6 class Ideone 7 { 8     public int top; 9     public Object[] objArray;10     11     //初始化12     public Ideone(int defaultSize)13     {14         objArray = new Object[defaultSize];15         top = -1;16     }17     18     //判断是否为空19     public boolean isEmpty()20     {21         boolean flag = false;22         if(top == -1)23         {24             flag = true;25         }26         return flag;27     }28     29     //获取栈顶元素30     public Object getTop()31     {32         if(!isEmpty())33         {34             return objArray[top];35         }36         System.out.println("栈为空");37         return null;38     }39     //栈顶插入数据40     public void push(Object obj)41     {42         if(top + 1 >= objArray.length)43         {44             System.out.println("栈已满,无法添加"+obj);45             return ;46         }47         objArray[top+1] = obj;48         top++;49     }50     51     //栈顶弹出数据52     public Object pop()53     {54         if(isEmpty())55         {56             System.out.println("栈已空");57             return null;58         }59         Object obj = objArray[top];60         objArray[top--] ="";61         return obj;62     }63     64     public static void main (String[] args) throws java.lang.Exception65     {66         // your code goes here67         Ideone s = new Ideone(2);68         s.push("a");69         s.push("b");70         s.push("c");71         System.out.println(s.getTop());72         System.out.println(s.pop());73         System.out.println(s.getTop());74         s.pop();75         System.out.println(s.getTop());76     }77 }

 

顺序表代码