Java棧(陣列實現)
阿新 • • 發佈:2019-01-07
/**
* 用陣列實現棧,最主要的是要在類的內部定義一個數組,
* 並且這個陣列要具有一定的大小,要在定義棧的時候定義好
*/
public class ArrayStack
{
private static final String TAG = "ArrayStack";
private Object[] contents;
private int top = -1;
private int bottom = -1;
private int SIZE = 10;//有一個初始值大小
public ArrayStack()
{
contents = new Object[SIZE];
top = -1;
}
public int push(Object obj) throws Exception
{
if (top > SIZE) throw new Exception("棧已經滿了!");
top++;
contents[top] = obj;
return top;
}
public Object pop() throws Exception
{
if (top == bottom) throw new Exception("棧已經空了!");
Object obj = contents[top];
contents[top] = null;
top--;
return obj;
}
public boolean isEmpty()
{
return top == bottom;
}
public int getSize()
{
return top + 1;
}
public void display() throws Exception
{
if (getSize() == 0) throw new Exception("空棧!");
for (int i=getSize()-1;i>=0;i--)
{
System.out.print(contents[i].toString() + "->");
}
System.out.println("");
}
public static void main(String[] args) throws Exception
{
ArrayStack as = new ArrayStack();
//as.display();
as.push("你好");
as.push("q");
as.push("werewrwer");
as.push("weee");
as.push("we123");
as.push("ertte");
as.push("ggmt");
as.display();
as.pop();
System.out.println(as.getSize());
as.pop();
as.display();
}
}