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 閱讀(138)
評論(0) 編輯 收藏