具体实现:在链表中使用节点存储数据,并使用引用串联各个元素。每个节点除了存储数据本身之外,还需要额外存储下一个节点的地址。
添加、删除、查找操作的编码如下:
public class LinkedList {
private Node head = null; // 整个链表的头指针
public void insert(Node a, Node b) { // 在节点a后面插入新节点b
if (a == null) { //在链表的头部插入添加数据b
b.next=head;
head=b;
} else {
b.next = a.next;
a.next = b;
}
}
// 删除已知前驱节点为a的节点b,b的前驱节点为a
public void remove(Node a, Node b) {
// 如果a为null则表示删除头节点b
if (a == null) {
head=head.next;
} else
a.next = b.next;
}
//删除存储的数据值为value的节点
public void remove(int value){
Node q=head;
Node p=null;
//遍历整个单向链表,查询具体存放数据为value的节点
while(q!=null && q.data!=value){
p=q;
q=q.next;
}
if(q!=null){
if(p==null)
head=q.next;
else
p.next=q.next;
}
}
//查找存储数据为 value的节点
public Node find(int value){
Node p=head;
while(p!=null && p.data!=value){
p=p.next;
}
return p;
}
//获取指定下标的节点
public Node get(int index){
Node p=head;
int res=0;
while(p!=null && res!=index){
res++;
p=p.next;
}
return p;
}
public static class Node {
private int data;//具体存储的数据
private Node next;
public Node(int data, Node next) {
super();
this.data = data;
this.next = next;
}
@Override
public String toString() {
return "Node [data=" + data + ", next=" + next + "]";
}
}
}