Java 单链表删除指定值节点算法
public class ListNode { int val; ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public class Solution { public ListNode deleteNodes(ListNode head, int x) { if (head == null) { return null; }
// 删除头部所有值为x的节点
while (head != null && head.val == x) {
head = head.next;
}
ListNode curr = head;
ListNode prev = null;
// 删除中间和尾部所有值为x的节点
while (curr != null) {
if (curr.val == x) {
if (prev != null) {
prev.next = curr.next;
}
} else {
prev = curr;
}
curr = curr.next;
}
return head;
}
}
原文地址: https://www.cveoy.top/t/topic/pgUG 著作权归作者所有。请勿转载和采集!