风故故,也依依

Stand still in the wind.

导航

Java数据结构(2)---单链表

interface List
{
public void insert(int i,Object obj) throws Exception;   //插入
public Object delete(int i) throws Exception;            //删除
public Object getData(int i) throws Exception;           //取数据元素
public int size();                                       //求元素个数
public boolean isEmpty();                                //是否空
}

//单链表结点类

class Node
{
Object element;   //数据元素
Node next;       //表示下一个结点的对象引用

Node(Node nextval)   //用于头结点的构造函数1
{
   next = nextval;
}

Node(Object obj,Node nextval)   //用于其他结点的构造函数2
{
   element = obj;
   next = nextval;
}

public Node getNext()   //取next
{
   return next;
}

public void setNext(Node nextval)   //置next
{
   next = nextval;
}

public Object getElement()    //取element
{
   return element;
}

public void setElement(Object obj)   //置element
{
   element = obj;
}

public String toString()   //转换element为String类型
{
   return element.toString();
}
}

//单链表类

class LinList implements List
{
Node head;      //头指针
Node current;   //当前结点位置
int size;       //数据元素个数

LinList()       //构造函数
{
   head = current = new Node(null);
   size =0;
}

public void index(int i) throws Exception
{ //定位到第i个结点(以0开始记起)
      if(i < -1 || i > size-1)
      {
    throw new Exception("参数错误!");
   }
   if(i == -1) return;
   current = head.next;
   int j = 0;
   while((current != null) && j < i)
   {
    current = current.next;
    j++;
   }
     }

     public void insert(int i,Object obj) throws Exception
     {
   if(i < 0 || i > size)
   {
    throw new Exception("参数错误!");
   }
   index(i-1);
   current.setNext(new Node(obj,current.next));
   size++;
}

public Object delete(int i) throws Exception
{
   if(size == 0)
   {
    throw new Exception("链表已空无元素可删除!");
   }
   if(i < 0 || i > size-1)
   {
    throw new Exception("参数错误!");
   }
   index(i-1);
   Object obj = current.next.getElement();
   current.setNext(current.next.next);
   size--;
   return obj;
}

public Object getData(int i) throws Exception
{
      if(i < -1 || i > size-1)
      {
    throw new Exception("参数错误!");
   }
   index(i);
   return current.getElement();
}

public int size()
{
   return size;
}

public boolean isEmpty()
{
   return size == 0;
}
}

/* 主函数
* 删除数列{1,2,3,4,5,6,7,8,9,10}里的元素5
*/

public class LinListTest
{
public static void main(String args[])
{
   LinList linList = new LinList();
   int n = 10;
   try
   {
    for(int i = 0;i < n;i++)
    {
     linList.insert(i,new Integer(i+1));
    }

    linList.delete(4);

    for(int i =0;i<linList.size;i++)
    {
     System.out.print(linList.getData(i)+"   ");
    }
   }
   catch(Exception e)
   {
    System.out.println(e.getMessage());
   }
}
}

posted on 2007-05-04 10:50  jadmin  阅读(278)  评论(0编辑  收藏  举报