链式存储结构
结点在存储器中的位置是任意的,即逻辑上相邻的数据元素在物理上不一定相邻。
单链表的存储映像
单向链表的每个数据项存储的都是 数据 + 下一个数据地址 ;双向链表存储的是 上一个数据地址 + 数据 + 下一个数据地址
单向链表的实现
public class SingleLinkedList {
/*
* 结点类
*/
private class Node{
private Object data;
private Node next;
public Node(Object data,Node next) {
this.data = data;
this.next = next;
}
public Node(Object data) {
this.data = data;
this.next = null;
}
}
/*
* 头结点
*/
private Node head;
private int size;//链表中有数据的节点的个数
/*
* 创建一个链表对象 只有头结点而且是一个空结点
*/
public SingleLinkedList() {
head = new Node(null);
}
public void add(Object obj) {
Node n = new Node(obj);
if(size == 0 ) {
head.next = n;
}else {
Node temp = head.next;
head.next = n;
n.next = temp;
}
size++;
}
/*
* 获取链表的元素
*/
public Object getValue(int index) {
if(index <= size) {
Node temp = head;
int i = 0 ;
while(temp != null) {
if(i == index ) {
return temp.data;
}
i++;
temp = temp.next;
}
return null;
}
return null;
}
public void deleteNode(Object obj) {
Node p = head;
Node q = head.next;
while(q != null){
if(q.data.equals(obj)){
p.next = q.next;
size--;
}else{
p = q;
q = q.next;
}
}
}
/*
* 获取链表的长度
*/
public int getSize() {
return size;
}
public void print() {
Node temp = head.next;
while(temp!=null) {
System.out.print(temp.data);
temp = temp.next;
}
System.out.println();
}
}
public class Test {
public static void main(String[] args) {
SingleLinkedList sl = new SingleLinkedList();
sl.add("aa");
sl.add("bb");
sl.add("cc");
sl.add("dd");
sl.print();
System.out.println(sl.getSize());
Object obj = sl.getValue(3);
System.out.println(obj);
sl.deleteNode("dd");
System.out.println(sl.getSize());
sl.print();
}
}
单向链表的删除图示