具体实现
----------------------------------------------------------------------------------------------------------------------
package LinkListDemo;
public interface List {
public int size();
public boolean empty();
public void insert(int index,Object obj) throws Exception;
public void delete(int index)throws Exception;
public Object get(int index)throws Exception;
}
-----------------------------------------------------------------------------------------------------------------
package LinkListDemo;
public class LinkList implements List {
Node head;//头指针
Node current;//当前结点对象
int size;//结点个数
//初始化一个空链表
public LinkList(){
this.head = current= new Node(null);
this.size=0;
}
//定位函数
public void index(int index) throws Exception{
if(index<-1||index>size-1){
throw new Exception("参数错误");
}
//说明在头结点之后操作
if(index == -1) return;
current =head.next;
int j = 0;//循环变量
while(current != null&& j<index){
current = current.next;
j++;
}
}
public int size() {
return this.size;
}
public boolean empty() {
return size==0;
}
public void insert(int index, Object obj) throws Exception {
if(index<0||index>size){
throw new Exception("参数错误");
}
index(index-1);
current.setNext(new Node(obj, current.next));
size++;//(可以在这里来改变size)
}
public void delete(int index) throws Exception {
if(empty()){
throw new Exception("链表为空");
}
if(index<0||index>size){
throw new Exception("参数错误");
}
index(index-1);//定位到要操作对象的前一个对象
current.setNext(current.next.next);
size--;
}
public Object get(int index) throws Exception {
if(index<0||index>size){
throw new Exception("参数错误");
}
index(index);
return current.getElement();
}
}
--------------------------------------------------------------------------------------------------------------------------------------------
package LinkListDemo;
public class Test {
public static void main(String[] args) throws Exception{
LinkList list = new LinkList();
for(int i=0;i<10;i++){
int temp = (int) (((Math.random())*100)%100);
list.insert(i, temp);
System.out.print(list.get(i)+" ");
}
list.delete(4);
System.out.println("-----删除第五个元素后----");
for(int i=0;i<list.size;i++){
System.out.print(list.get(i)+" ");
}
}
}