/**
* @author*simonws
*/
public class StackNode< T> {
//要存儲的信息
private T info;
public StackNode()
{
this(null);
}
public StackNode(T info)
{
this.info = info;
}
//set方法
public void set(T info)
{
this.info = info;
}
//get方法
public T get()
{
return info;
}
}
而後,是棧的實現了,這纔是關鍵:
/**
* @author*simonws
*
*/
public class Stack< T> {
//儲存數據的棧
private StackNode< T> stack[];
//棧的最大容量
private int maxSize;
//棧的當前容量
private int size;
//不傳參數,默認棧的最大容量爲100
public Stack()
{
this.maxSize = 100; this
}
public Stack(int maxSize)
{
//若是傳入的參數小於或等於0,則設置最大容量爲100
if(maxSize <= 0)
maxSize = 100;
this.maxSize = maxSize;
}
//初始化棧,在堆中先申請好內存空間
public void initStack()
{
stack = new StackNode[maxSize];
//棧的當前大小爲0
size = 0;
}
//棧的基本方法之一,得到棧頂元素
public StackNode< T> getTop()
{
//棧中沒有元素,則返回空
if(size == 0)
return null;
return stack[size-1];
}
//棧的基本方法之一,入棧
public boolean push(StackNode< T> stackNode)
{
//棧已滿,入棧失敗
if(size >= maxSize)
return false;
size++;
stack[size] = stackNode;
return true;
}
//棧的基本方法之一,出棧
public StackNode< T> pop()
{
//若是棧已空,則返回null
if(size <= 0)
return null; 內存
StackNode< T> pop = stack[size-1];get
stack[size-1] = null;
size--; it
return pop ;
}
//棧是否爲空
public boolean isEmpty()
{
if(size <= 0)
return true;
return false;
}
//棧的基本方法之一,遍歷棧
public void traverse()
{
for(int i = 0; i < size; i++)
{
System.out.println(stack[i].get());
}
}
public static void main(String []agrs)
{
Stack< String> stack = new Stack< String>();
stack.initStack();
stack.push(new StackNode< String>("Anybody1"));
stack.push(new StackNode< String>("Anybody2"));
stack.push(new StackNode< String>("Anybody3"));
stack.traverse();
}
}
class