链表是一种时常会用到的数据结构,因此扎实掌握链表的基本操作则显得十分重要。
以下是关于几个常见链表操作的动态图解,大家可以收藏起来,方便以后复习之用。
链表插入
插入空链表
Node newNode = newNode(data);
head = newNode;
newNode.next = null;
插入链表中央
Node newNode = new Node(data);
Node current = head;
// 遍历寻找插入位置
while (!current.equals(targetNode)) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
插入链表开头
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
插入链表末尾
Node newNode = new Node(data);
Node current = head;
// 遍历到链表末尾
while (current.next != null) {
current = current.next;
}
current.next = newNode;
newNode.next = null;
链表删除
删除中间节点
Node prev = null;
Node current = head;
// 遍历寻找目标节点
while (!currentNode.equals(targetNode)) {
prev = current;
current = current.next;
}
prev.next = current.next;
删除头节点
head = head.next;
删除末尾节点
同删除中间节点代码一样
Node prev = null;
Node current = head;
// 遍历寻找目标节点
while (!currentNode.equals(targetNode)) {
prev = current;
current = current.next;
}
prev.next = current.next;
翻转链表
public class Main {
public static void reverseLinkedList(LinkedList list) {
if (list.head == null || list.head.next == null) {
return;
}
Node prev = null;
Node current = list.head;
Node next = current.next;
while (current != null) {
current.next = prev;
if (next == null) {
break;
}
prev = current;
current = next;
next = next.next;
}
list.head = current;
}
}
class Node {
public Node next;
public int val;
public Node(int val) {
this.val = val;
this.next = null;
}
}
class LinkedList {
public Node head;
}