剑指 Offer 18_2 删除链表节点
1 题目
- 给定单向链表的头指针和一个节点值,定义一个函数在
O(1)
时间内删除该节点。
2 提示
- 题目保证链表中节点的值互不相同;
- 若使用
C
或 C++
语言,你不需要 free
或 delete
被删除的节点。
3 示例
// 示例 1
输入: head = [4,5,1,9],value=4
输出: [5,1,9]
// 示例 2
输入: head = [4,5,1,9],value=5
输出: [4,1,9]
// 示例 3
输入: head = [4,5,1,9],value=9
输出: [4,5,1]
// 示例 4
输入: head = [9], value=9
输出: null
4 解题思路
- 对于非尾节点,把下一个节点的内容覆盖要删除的节点,并删除下一个节点;
- 对于尾节点,先顺序查找,再删除。
5 复杂度分析
6 题解
public class JZ18_2_删除链表节点 {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
ListNode<Integer> node9 = new ListNode(9);
ListNode<Integer> node1 = new ListNode(1, node9);
ListNode<Integer> node5 = new ListNode(5, node1);
ListNode<Integer> node4 = new ListNode(4, node5);
if (0 == i) {
PrintUtils.getInstance().printListNode(node4);
PrintUtils.getInstance().printListNode(solution(node4, 4), "打印删除后的链表");
} else if (1 == i) {
PrintUtils.getInstance().printListNode(node4);
PrintUtils.getInstance().printListNode(solution(node4, 5), "打印删除后的链表");
} else if (2 == i) {
PrintUtils.getInstance().printListNode(node4);
PrintUtils.getInstance().printListNode(solution(node4, 9), "打印删除后的链表");
} else if (3 == i) {
PrintUtils.getInstance().printListNode(node9);
PrintUtils.getInstance().printListNode(solution(node9, 9), "打印删除后的链表");
}
}
}
private static ListNode<Integer> solution(ListNode<Integer> head, int value) {
if (null == head) return head;
if (head.val == value) return head.next;
ListNode<Integer> pre = head, curr = head.next;
while (null != curr && curr.val != value) {
pre = curr;
curr = curr.next;
}
if (null != curr) pre.next = curr.next;
return head;
}
}