标签:
//栈顶元素 public class StackElement<T> { private StackElement<T>nextElement; private T data; public StackElement(T data) { this.data=data; } public StackElement<T> getNextElement() { return nextElement; } public void setNextElement(StackElement<T> nextElement) { this.nextElement = nextElement; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
工具栈类:
public class SeqStack<T> { private StackElement<T> obj;//用来保存数据 private int size;//元素个数 public SeqStack() { this.size=0; } //向栈顶加入一个元素 public boolean push(T data) { if (data!=null) { StackElement<T>tempElement=new StackElement(data); tempElement.setNextElement(this.obj); this.obj=tempElement; tempElement=null;//回收 this.size++; return true; } return false; } //栈顶中弹出一个元素 public boolean pop() { if (this.size>0) { this.obj=this.obj.getNextElement(); this.size--; return true; } return false; } //清空栈 public void clear() { this.size=0; this.obj=null; } //得到栈顶元素 public T get() { return obj==null?null:obj.getData(); } //栈的大小 public int size() { return this.size; } public static void main(String []arg) { SeqStack<Integer> selStack=new SeqStack(); for(int i=0;i<10;i++) selStack.push(i); System.out.println("The size of the stack:"+selStack.size()); int size=selStack.size(); for(int i=0;i<size;i++) { System.out.println(selStack.get()); selStack.pop(); } } }运行结果:
不足之处,请指正。
标签:
原文地址:http://blog.csdn.net/yilip/article/details/44762995