链表是由一系列节点组成的数据结构,节点可以在运行过程中动态生成。每个节点都包括两部分内容:存储数据的数据域;存储下一个节点的指针域。由于链表是随机存储的,所以链表的插入的时间复杂度是O(1),查询的时间复杂度是O(n)。所以链表的特点是插入快,查询慢。链表有三种类型:单向链表、双向链表、循环链表。
单向链表操作-
查询:单向链表只可向一个方向遍历,一般在查找一个节点时需要从单向链表的第一个节点开始依次访问下一个节点,一直访问到需要的位置。
-
插入:对于单向链表的插入,只需将当前插入的节点设置为头节点,将Next指针指向原来的头节点即可。
-
删除:对于单向链表的删除,我们只需将该节点的上一个节点的Next指针指向该节点的下一个节点,然后删除该节点即可。
package datastructure;
public class SingleLinkedList {
private Node head;//头节点
private int length;//链表节点的个数
public static void main(String[] args) {
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.addHead(1);
singleLinkedList.addHead(2);
singleLinkedList.addHead(3);
System.out.println(singleLinkedList.delete(1));
System.out.println(singleLinkedList.find(2).data);
}
public Object addHead(Object obj){
//定义新节点
Node newNode = new Node(obj);
if(length == 0){
//链表为空,该节点设置为头节点
head = newNode;
}else{
//新节点设置为头节点,新节点的下一个节点设置为原来的头节点
newNode.next = head;
head = newNode;
}
//链表长度加1
length++;
return obj;
}
public boolean delete(Object value){
if(length == 0){
return false;
}
Node current = head;
Node previous = head;
//从前向后遍历
while (current.data != value){
//当前节点是尾节点
if(current.next == null){
return false;
}else{
previous = current;
current = current.next;
}
}
//如果删除的节点是头节点
if(current == head){
head = current.next;
length--;
}else{
//删除的节点不是头节点
previous.next = current.next;
length--;
}
return true;
}
public Node find(Object obj){
Node current = head;
int tempSize = length;
while (tempSize > 0){
if(obj.equals(current.data)){
return current;
}else{
current = current.next;
}
tempSize--;
}
return null;
}
private class Node{
private Object data;//每个节点的数据
private Node next;//每个节点指向下一个节点的数据
public Node(Object data) {
this.data = data;
}
}
}
执行结果:



