简体   繁体   中英

Removing the end node from a linked list

What am I missing to allow me to remove a node(boxcar) to the end of my linked list?

public void removeBoxcarFromEnd() {

    Boxcar prevcar = head;
    Boxcar nextcar = head;

    if (head.next == null) {
        int result = head.data;
        head = null;
        return result;
    }    
    else {
        while (nextcar.next() > 2)
        prevcar = nextcar;
        nextcar = nextcar.next();
    }
    prevcar.setNext(null);
    size--;
}

There are a few problems with this approach:

  • you're method is a void whereas you want to return the data of the last item?

  • your while loop doesn't use brackets ( {} ) nor indentation, therefore only prevcar = nextcar will be executed an infinite amount of times.

  • you use >2 ;

  • there is a cornercase where the linked list can be empty as well.

A probably better way to handle this:

public String removeBoxcarFromEnd() {
    String result;
    if(head == null) {  //empty list
        return null;      //or do something else? throw an exception?
    } else if (head.next() == null) {  //one element, remove it
        int result = head.data();
        head = null;
    }    
    else {  //more elements
        Boxcar prevcar = head, nextcar = head.next(), ffcar = nextcar.next();
        while (ffcar != null) {  //double next iteration
            prevcar = nextcar;
            nextcar = ffcar;
            ffcar = ffcar.next();
        }
        int result = nextcar.data(); //get result
        prevcar.setNext(null);       //remove it from the linked list
    }
    size--;
    return result;
}

Assuming you don't need to fetch data, only remove the last Boxcar :

public void removeBoxcarFromEnd() {
    Boxcar prevcar = head;
    Boxcar nextcar = head;

    if (head == null || head.next() == null) {
        return;
    }
    while (nextcar.next() != null) {
        prevcar = nextcar;
        nextcar = nextcar.next();
    }
    prevcar.setNext(null);
}

First we check for a null or one-element list; in those cases, there's nothing to do.

Next we walk the list until we get to the end (ie nextCar.next() returns null). At each step, we save the Boxcar that we're passsing.

When we exit the loop, prevcar points to the second-to-last car, and we can safely set its next variable to null .

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