思维导图
![](https://i-blog.csdnimg.cn/blog_migrate/107b63988f12043dfff9c44b4046c0dd.png)
是什么?
链表是通过‘指针’把一组零散的内存串联起来的‘数组’
干什么?
既生数组,何生链表?由于
数组需要一块连续的内存空间来存储数据,对内存的要求比较高,比如
申请一个100MB大小数据空间,
而有时内存中并没有那么多连续的空间,此时链表则有勇武之地。
怎么用?
常用的链表为单链表、双向链表、循环链表。
单链表
是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。
链表中的数据是以结点来表示的,元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。
有两个结点是特殊的,那就是第一个结点和最后一个结点,即头结点和尾结点,头结点用来记录链表的基地址,有了它我们就可以遍历得到整条链表,而尾节点最后指向的不是下一个结点,而是一个空的地址null。
优点:
在插入和删除的时候只需要修改上一个元素的指针即可,时间复杂度一下子从 O(n) 降到了 O(1)
缺点:
访问的复杂度变成了 O(n) 。
Java代码
public class SimpleLinkedList {
public Node head;// 定义一个头节点
public Node tail;//尾指针永远指向头节点
public int size = 0;// 节点的位置
class Node{
// 每个结点的构成:元素(数据元素的映象) + 指针(指示后继元素存储位置),
private Object data;
private Node next = null;
public Node(Object data){
this.data = data;
}
public Node(Object data,Node next ){
this.data = data;
this.next = next;
}
}
/**
* 头插法
*
* @param data
*/
public void addfrist(Object data) {
Node newnode = new Node(data);
newnode.next=head;
head=newnode;
size++;
}
/**
* 尾插法
*
* @param data
*/
public void addlast(Object data) {
if (head == null) {
head = new Node(data);
tail = head;
} else {
Node newL = new Node(data);
tail.next = newL;
tail = newL;
}
size++;
}
/**
* 获取链表长度
*/
public int size() {
Node cure = head;
while (cure != null) {
cure = cure.next;
}
return size;
}
/**
* 获取指定位置的节点元素
*
* @param index
* @return
*/
public Node getData(int index) {
if (index < 0 && index > size - 1) {
throw new IndexOutOfBoundsException("越界");
}
Node first = head;
for (int i = 0; i < size && first != null; i++, first = first.next) {
if (i == index) {
return first;
}
}
return null;
}
/**
* 从指定位置处插入数据
*
* @param data
* @param index
*/
public void insert(Object data, int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("索引超出线性表范围");
}
if ( head == null) {
addlast(data);
} else {
if (index == 0) {
addfrist(data);
} else {
Node k = getData(index - 1);
k.next = new Node(data, k.next);
size++;
}
}
}
/**
* 从指定位置处删除
*
* @param index
*/
public void Dell(int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("索引超出线性表范围");
}
Node del = null;
if (index == 0) {
del = head.next;
head = head.next;
} else {
Node neL = getData(index - 1);
del = neL.next;
neL.next = del.next;
del.next = null;
}
size--;
}
public static void main(String[] args)
{
SimpleLinkedList linkedList = new SimpleLinkedList();
linkedList.addfrist("aaa");
linkedList.addfrist("v");
linkedList.addfrist("c");
linkedList.insert(1,2);
System.out.println(linkedList.size());
for (Integer i =0;i<linkedList.size;i++){
System.out.println("index:"+i+",data:"+linkedList.getData(i).data);
}
}
}