"Prove safety offer" delete list node 13 interview questions Java version in O (1) time

This question is crucial to know before a node must traverse to find the end node, and the complexity of the overall time after doing so or O (1), and how to delete the list does not destroy a known node

    public ListNode delete(ListNode head, ListNode toBeDelete){
        //如果头节点为空或者只有一个节点
        if(head == null || head.next == null)return null;
        //如果要删除的节点在末尾
        if(toBeDelete.next == null){
            ListNode index = head;
            while(index.next!= toBeDelete){
                index = index.next;
            }
            index.next = index.next;
        }else{//要删除的节点不在末尾
            toBeDelete.val = toBeDelete.next.val;
            toBeDelete.next = toBeDelete.next.next;
        }
        return head;
    }

Guess you like

Origin www.cnblogs.com/czjk/p/11611530.html