18.1 在 O(1) 时间内删除链表节点

解题思路

① 如果该节点不是尾节点,那么可以直接将下一个节点的值赋给该节点,然后令该节点指向下下个节点,再删除下一个节点,时间复杂度为 O(1)。

18.1 在 O(1) 时间内删除链表节点 - 图1

② 否则,就需要先遍历链表,找到节点的前一个节点,然后让前一个节点指向 null,时间复杂度为 O(N)。

18.1 在 O(1) 时间内删除链表节点 - 图2

综上,如果进行 N 次操作,那么大约需要操作节点的次数为 N-1+N=2N-1,其中 N-1 表示 N-1 个不是尾节点的每个节点以 O(1) 的时间复杂度操作节点的总次数,N 表示 1 个尾节点以 O(N) 的时间复杂度操作节点的总次数。(2N-1)/N ~ 2,因此该算法的平均时间复杂度为 O(1)。

  1. public ListNode deleteNode(ListNode head, ListNode tobeDelete) {
  2. if (head == null || tobeDelete == null)
  3. return null;
  4. if (tobeDelete.next != null) {
  5. // 要删除的节点不是尾节点
  6. ListNode next = tobeDelete.next;
  7. tobeDelete.val = next.val;
  8. tobeDelete.next = next.next;
  9. } else {
  10. if (head == tobeDelete)
  11. // 只有一个节点
  12. head = null;
  13. else {
  14. ListNode cur = head;
  15. while (cur.next != tobeDelete)
  16. cur = cur.next;
  17. cur.next = null;
  18. }
  19. }
  20. return head;
  21. }

18.1 在 O(1) 时间内删除链表节点 - 图3