首先要清楚链表的结构特点:前后相连,与顺序结构相比最大特点是所存取的部分在内存中不连续,前一个元素对象指向下一个,在c和c++中这种指向关系用指针实现,而在java中是通过对象引用传递实现。
结点是链表中最基本的成员,可通过编写类实现链表中的结点:
class Node {
Object data;
Node next; //指向下一个结点
}
完整的链表还需要定义:表头,表头包含指向第一个结点的指针Head和指向当前结点的指针Pointer(存储指向它的前驱结点的指针,当其值为null时表示当前结点是第一个结点,要得到当前结点,可定义一个方法cursor(),返回值是指向当前结点的指针);还可以增加指向链表尾部的指针Tail,便于在链表尾部增加结点;另外可用一个域Length表示链表的大小。这里用一个类List实现链表结构。
链表的常见操作为:插入,删除结点等,对应的方法有以下:
public class List {
private Node Head = null;
private Node Tail = null;
private Node Pointer = null;
private int Length = 0;
//清空链表
public void deleteAll() {
Head = null;
Tail = null;
Pointer = null;
Length = 0;
}
//链表复位,使第一个结点成为当前结点
public void reset() {
Pointer = null;
}
//判断链表是否为空
public boolean isEmpty() {
return(Length == 0);
}
//判断当前结点是否为最后一个结点
public boolean isEnd() {
if (Length == 0)
throw new NullPointerException();
else if (Length == 1)
return true;
else
return(cursor() == Tail);
}
//返回当前结点的下一个结点的值,并使其成为当前结点
public Object nextNode() {
if (Length == 1)
throw new NoSuchElementException();
else if (Length == 0)
throw new NullPointerException();
else {
Node temp = cursor();
Pointer = temp;
if (temp != Tail)
return(temp.next.data);
else
throw new NoSuchElementException();
}
}
//返回当前结点的值
public Object currentNode() {
Node temp = cursor();
return temp.data;
}
//在当前结点前插入一个结点,并使其成为当前结点
public void insert(Object d) {
Node e = new Node(d);
if (Length == 0) {
Tail = e;
Head = e;
}
else {
Node temp = cursor();
e.next = temp;
if (Pointer == null)
Head = e;
else
Pointer.next = e;
}
Length++;
}
//返回链表的大小
public int size() {
return(Length);
}
//将当前结点移出链表,下一个结点成为当前结点,如果移出的结点是最后一个结点,则第一个结点成为当前结点
public Object remove() {
Object temp;
if (Length == 0)
throw new NoSuchElementException();
else if (Length == 1) {
temp = Head.data;
deleteAll();
}
else {
Node cur = cursor();
temp = cur.data;
if (cur == Head)
Head = cur.next;
else if (cur == Tail) {
Pointer.next = null;
Tail = Pointer;
reset();
}
else
Pointer.next = cur.next;
Length--;
}
return temp;
}
//返回当前结点的指针
private Node cursor() {
if (Head == null)
throw new NullPointerException();
else if (Pointer == null)
return Head;
else
return Pointer.next;
}
}