大纲
1.单链表基础与构造方法
1.1 链表的内部结构
链表中每个节点内部的 “生态环境”。
单向链表就像一个铁链一样,元素之间相互连接,包含多个结点,每个节点有一个指向后继结点的next指针。表中的最后一个元素的next指向null。如下图:
1.2 创建链表
根据面向对象的理论,在 Java 里规范的链表应该这么定义:
public class ListNode {
private int data;
private ListNode next;
public ListNode(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
1.3 遍历链表
对于单链表,不管进行什么操作,一定是从头开始逐个向后访问,所以操作之后还能找到表头非常重要。一定要注意“狗熊掰棒子”问题,也就是只顾当前位置而将标记表头的指针丢掉了。
public static int getListLength(Node head) {
int length = 0;
Node node = head;
while (node != null) {
length++;
node = node.next;
}
return length;
}
1.4 链表插入
(1)在链表的表头插入
链表表头插入新结点非常简单,容器出错的是经常会忘了head需要重新指向表头。
(2)在链表中间插入
在中间位置插入,我们必须先遍历找到要插入的位置,然后将当前位置接入到前驱结点和后继结点之间,但是到了该位置之后,我们却不能获得前驱结点了,也就无法将结点接入进来了。这就好比一边过河一边拆桥,结果自己也回不去了。
想一想为什么不能颠倒顺序?
(3)在单链表的结尾插入结点
表尾插入就比较容易了,我们只要将尾结点指向新结点就行。
综上,我们写出的链表的插入方法如下所示:
/**
* 链表插入
*
* @param head 链表头结点
* @param nodeInsert 待插入结点
* @param position 待插入位置,从1开始
* @return 插入后得到的链表头结点
*/
public static ListNode insertNode(ListNode head, ListNode nodeInsert, int position) {
if (head == null) {
// 这里可以认为待插入的头结点就是链表的头结点,也可以抛出不能插入的异常
return nodeInsert;
}
// 已经存放的元素个数
int size = getLength(head);
if (position > size + 1 || position < 1) {
System.out.println("位置参数越界");
return head;
}
// 表头插入
if (position == 1) {
nodeInsert.next = head;
// 这里可以直接 return nodeInsert;
// 还可以这么写
head = nodeInsert;
return head;
}
ListNode pNode = head;
int count = 1;
// 这里 position 被上面的 size 给限制住了,不用考虑 pNode=null
while (count < position - 1) {
pNode = pNode.next;
count++;
}
nodeInsert.next = pNode.next;
pNode.next = nodeInsert;
return head;
}
1.5 链表删除
(1)删除表头结点
删除表头元素还是比较简单的,一般只要执行 head=head.next 就行了。
(2)删除最后一个结点
删除的过程不算复杂,也是要找到删除结点的前驱结点,这里同样要在提前一个位置判断,例如下图中要删除5,其前驱结点是4。遍历的时候需要判断 cur.next 是否为5,如果是,则只要执行cur.next=null即可,此时结点5变得不可达,最终会被JVM回收掉。
(3)删除中间结点
删除中间结点时,也要用cur.next来比较,找到位置后,将cur.next指针的值更新为cur.next.next即可。
完整实现:
/**
* 删除节点
*
* @param head 链表头结点
* @param position 删除节点的位置,取值从1开始
* @return 删除后的链表头结点
*/
public static ListNode deleteNode(ListNode head, int position) {
if (head == null) {
return null;
}
int size = getLength(head);
// 思考一下,这里为什么是size,而不是size+1
// 因为 插入可以在尾结点之后,删除只能在尾结点之前
if (position > size || position < 1) {
System.out.println("输入的参数有误");
return head;
}
if (position == 1) {
// curNode 就是链表的新head
return head.next;
} else {
ListNode cur = head;
int count = 1;
while (count < position - 1) {
cur = cur.next;
count++;
}
ListNode curNode = cur.next;
cur.next = curNode.next;
// 上面两行可以直接简化为: cur.next=cur.next.next;
}
return head;
}