java如何删除链表
删除链表的方法
在Java中删除链表通常涉及删除特定节点或清空整个链表。以下是几种常见情况的实现方法:
删除链表的头节点
若需要删除链表的第一个节点,只需将头指针指向下一个节点:
public void deleteHead(ListNode head) {
if (head != null) {
head = head.next;
}
}
删除链表的尾节点
删除尾节点需要遍历链表至倒数第二个节点,并将其 next 设为 null:
public void deleteTail(ListNode head) {
if (head == null || head.next == null) {
head = null;
return;
}
ListNode current = head;
while (current.next.next != null) {
current = current.next;
}
current.next = null;
}
删除指定值的节点
遍历链表,找到目标节点后调整指针跳过该节点:
public void deleteNode(ListNode head, int val) {
if (head == null) return;
if (head.val == val) {
head = head.next;
return;
}
ListNode current = head;
while (current.next != null && current.next.val != val) {
current = current.next;
}
if (current.next != null) {
current.next = current.next.next;
}
}
清空整个链表
直接将头节点设为 null,Java的垃圾回收机制会自动处理剩余节点:

public void clearLinkedList(ListNode head) {
head = null;
}
注意事项
- 删除操作需检查边界条件(如空链表或单节点链表)。
- 若链表为双向链表,需额外处理
prev指针。 - 删除中间节点时,时间复杂度为 O(n),而删除头节点为 O(1)。
以上方法适用于单链表,若为双向链表或其他结构,需相应调整指针逻辑。






