用链表实现栈的代码
来源:优易学  2011-12-22 19:30:02   【优易学:中国教育考试门户网】   资料下载   IT书店
  实现代码如下:
  interface StackPK{
  void Push(Object obj);
  Object Pop();
  boolean isEmpty();
  int Size();
  }
  public class LinkStack implements StackPK{
  private class SLLNode{
  private Object data;
  private SLLNode next;
  SLLNode(){}
  SLLNode(Object obj){
  data=obj;
  }
  public void setData(Object o){
  if(o==null)
  throw new IllegalArgumentException("object is null");
  data=o;
  }
  public Object getData(){
  return data;
  }
  public void setNext(SLLNode n){
  next=n;
  }
  public SLLNode getNext(){
  return next;
  }
  public String toString(){
  return (String)data;
  }
  }
  private SLLNode top;
  public LinkStack(){
  top=null;
  }
  public void Push(Object obj){
  if(obj==null)
  throw new IllegalArgumentException("n is null");
  if(top==null)
  {
  SLLNode temp=new SLLNode(obj);
  top=temp;
  }
  else
  {
  SLLNode temp=new SLLNode(obj);
  temp.setNext(top);
  top=temp;
  }
  }
  public Object Pop(){
  SLLNode temp;
  if(top==null)
  throw new IllegalArgumentException("stack is empty");
  temp=top;
  top=top.getNext();
  return temp.getData();
  }
  public boolean isEmpty(){
  if(top == null)
  return true;
  else
  return false;
  }
  public int Size(){
  SLLNode cnt;
  cnt=top;
  int count=0;
  if(cnt == null)
  return 0;
  while(cnt != null){
  ++count;
  cnt=cnt.getNext();
  }
  return count;
  }
  public static void main(String[] args){
  LinkStack ls=new LinkStack();
  Object[] arr=new String[]{"liangming","gaojie","liangbing","wuxia","zhangjun"};
  for(int i=0;i<arr.length;i++)
  ls.Push(arr[i]);
  while(ls.Size()>0)
  {
  System.out.println(ls.Pop());
  }
  }
  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训