//单向链表类
publicclassLinkList{
//结点类
publicclassNode{
publicObject data;
publicNode next;
publicNode(Object obj,Node next){
this.data = obj;
this.next = next;
}
}
Node head; //记录头结点信息即可(头结点下标为-1)
int size;
publicLinkList()
{
this.head =newNode(null, null);
this.size =0;
}
//定位
publicNode locate(int index) throws Exception
{
//容错性
if(index <-1|| index > size)
thrownewException("参数错误!");
//定位到temp指向第index个(index为下标,从0开始)
Node temp = head;
for(int i =-1; i < index; i++)
if(temp != null)
temp = temp.next;
return temp;
}
publicvoiddelete(int index) throws Exception
{
//容错性
if(isEmpty())
thrownewException("链表为空,无法删除!");
if(index <0|| index > size -1)
thrownewException("参数错误!");
Node temp = locate(index -1); //定位到要操作结点的前一个结点对象
temp.next = temp.next.next;
size--;
}
publicvoid insert(int index,Object obj) throws Exception
{
//容错性
if(index <0|| index > size )
thrownewException("参数错误!");
Node temp = locate(index -1); //定位到要操作结点的前一个结点对象
Node p =newNode(obj,temp.next);
temp.next = p;
size++;
}
public boolean isEmpty(){
return size==0;
}
publicint size(){
returnthis.size;
}
}
publicclassTest{
publicstaticvoid main(String[] args) throws Exception{
LinkListlist=newLinkList();
for(int i =0; i <10; i++){
int temp =((int)(Math.random()*100))%100;
list.insert(i, temp);
System.out.print(temp +" ");
}
list.delete(4);
System.out.println("\n"+"after deleting the 5th number:");
for(int i =0; i <list.size; i++){
System.out.print(list.locate(i).data.toString()+" ");
}
}
}
输出:
29263748496266877839
after deleting the 5th number:
292637486266877839