很多高级语言不具备指针的概念,这时在实现链表的功能时就可以使用静态链表来完成。
静态链表就是一个使用数组来描述链表的方法,使用数组的下标作为游标来代替指针的概念。每一个节点除了储存数据外还必须有一个字段用来储存下一个节点的下表。这样同样能够实现链表方便插入和删除的特点。
下面是使用java来实现静态链表的代码示例
import java.util.Scanner;
public class StaticLinkList {
private static Note []notes = new Note[10000];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//假设由终端输入集合元素,先输入集合A的元素创建加入链表la,然后输入集合B的元素,查找链表la
//如果la中存在元素与输入的元素相同则删除la中的该元素,如果没有相同则将此元素插入到la之后
initLinkList();
int head = malloc();
int tail = head;
int n = sc.nextInt(); //集合A有n个元素
for ( int i = 0; i < n; i ++) {
int a = sc.nextInt();
int p = malloc();
notes[p].data = a;
notes[p].cursor = 0;
notes[tail].cursor = p;
tail = p;
}
int m = sc.nextInt();
for ( int i = 0; i < m; i ++) {
int a = sc.nextInt();
int j = notes[head].cursor;
int b = head;
while ( j != notes[tail].cursor && a != notes[j].data) {
b = j;
j = notes[j].cursor;
}
if (j == notes[tail].cursor) {
int p = malloc();
notes[p].data = a;
notes[p].cursor = notes[tail].cursor;
notes[tail].cursor = p;
} else {
notes[b].cursor = notes[j].cursor;
free(j);
if (j == tail) {
tail = b;
}
}
}
show(head);
}
private static void initLinkList() {
//创建未使用节点的链表
for (int i = 0; i < notes.length - 1; i ++) {
notes[i] = new Note(i+1);
}
notes[notes.length-1] = new Note(0);
}
private static int malloc() {
//分配节点
if (notes[0].cursor == 0) {
//除头节点外都已经使用完毕
return -1;
}
int i = notes[0].cursor;
notes[0].cursor = notes[i].cursor;
return i;
}
private static void free(int i) {
//回收i节点
notes[i].cursor = notes[0].cursor;
notes[0].cursor = i;
}
private static void show(int head) {
int i = notes[head].cursor;
System.out.print("[");
while ( i != 0) {
System.out.print(notes[i].data + ",");
i = notes[i].cursor;
}
System.out.println("]");
}
}
class Note {
public int data;
public int cursor;
public Note(int cursor) {
this.cursor = cursor;
}
}