关键词:头结点,头指针,结点,指向下一个结点的指针
用Java语言创建一个单链表就是创建一个结点类Node和一个单链表类LinList,然后在你需要一个单链表的时候,在你程序的某个方法内new一个LinList类的对象,然后再例如可以调用该对象的insert()方法往这个单链表内插入数据。
1.单链表的结点类设计(对单个结点的设计,通常包含数据域和指针域两个属性)
public class Node{
Object data;//数据域
Node next;//指针域
Node(Node nextval){
next = nextval;
}
Node(Object obj,Node nextval){
data = obj;
next = nextval;
}
public Node getNext(){
return next;
}
public void setNext(Node nextval){
next = nextval;
}
public Object getElement(){
return data;
}
public void setElement(Object obj){
data = obj;
}
}
2.单链表类的设计(设计单链表类就是操作结点的)
public class LinList {
//成员变量
Node head; //头指针
Node current; //当前结点位置
int size; //数据元素个数
//构造函数
LinList(){
head = current = new Node(null);
size = 0;
}
//定位第i个结点,若i=0则表示头结点
//若成功定位到该结点,则使指针current指向该结点
public void index(int i) throws Exception{
if(i == -1) return;
current = head.next;
int j = 0;
while((current != null) && j < i){
current=current.next;//若成功定位到该结点
j ++;
}
}
//在第i个结点前插入一个新结点
public void insert(int i,Object obj) throws Exception{
index(i - 1);
current.setNext(new Node(obj,current.next));
size ++;
}
//删除第i个结点
public Object delete(int i) throws Exception{
index(i - 1);
Object obj = current.next.getElement();
current.setNext(current.next.next);
size --;
return obj;//返回被删除结点的数据域
}
}