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

删除链表的一个结点,用下一个结点覆盖掉要删除的结点,再释放掉要删结点的下一个结点的内存

Java:

 1 public ListNode deleteNode(ListNode head, ListNode tobeDelete) {
 2     if (head == null || head.next == null || tobeDelete == null) return null;
 3     if (tobeDelete.next != null) {
 4         // 要删除的节点不是尾节点
 5         ListNode next = tobeDelete.next;
 6         tobeDelete.val = next.val;
 7         tobeDelete.next = next.next;
 8     } else {
 9         ListNode cur = head;
10         while (cur.next != tobeDelete) cur = cur.next;
11         cur.next = null;
12     }
13     return head;
14 }
原文地址:https://www.cnblogs.com/mengchunchen/p/8916773.html