简体   繁体   中英

would this code delete the last node in linked list?

Its just a code snippet, but considering everything else has been coded right, would this logically delete the last node? Or is my logic faulty?

Question answered.

Currently, the code would throw an exception as current would be null after exiting the while loop. The correct version of the method (with deletion from a specific position) might look something like the following:

public static Node delete(Node head, int position)
{
    Node traverse = head;
    if(position == 0) { 
        //remember this case
        head = head.next;
        return head;
    }

    for(int i = 1; i < position; i++)
        traverse = traverse.next;

    Node deleteit = traverse.next; //want to skip over this node
    traverse.next = deleteit.next; 

    return head;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM