4
头图

Delete a linked list node in O(1) time

Topic description

Delete a linked list node in O(1) time.

scheme: If the node is not a tail node, you can directly assign the value of the next node to the node, then make the node point to the next node, and then delete the next node, the time complexity is O(1). Otherwise, you need to traverse the linked list first, find the previous node of the node, and then let the previous node point to null, and the time complexity is O(N).

Topic link : [Delete a linked list node in O(1) time]()

code

/**
 * 在 O(1) 时间内删除链表节点
 */
public class Jz69 {

    /**
     * 方案:
     * 如果该节点不是尾节点,那么可以直接将下一个节点的值赋给该节点,然后令该节点指向下下个节点,再删除下一个节点,时间复杂度为 O(1)。
     * 否则,就需要先遍历链表,找到节点的前一个节点,然后让前一个节点指向 null,时间复杂度为 O(N)。
     *
     * @param head
     * @param tobeDelete
     * @return
     */
    public ListNode deleteNode(ListNode head, ListNode tobeDelete) {
        if (head == null || tobeDelete == null) {
            return null;
        }
        if (tobeDelete.next != null) {
            // 要删除的节点不是尾结点
            ListNode next = tobeDelete.next;
            tobeDelete.val = next.val;
            tobeDelete.next = next.next;
        } else {
            if (head == tobeDelete) {
                // 只有一个节点
                head = null;
            } else {
                ListNode cur = head;
                while (cur.next != tobeDelete) {
                    cur = cur.next;
                }
                cur.next = null;
            }
        }

        return head;
    }

    public static void main(String[] args) {
    
    }
}
[Daily Message] Dou Yanshan has a righteous formula; he teaches five sons, and he is famous.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!