Reputation: 41
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--;
}
Upvotes: 2
Views: 105
Reputation: 3914
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 (i.e. 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
.
Upvotes: 0
Reputation: 476584
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;
}
Upvotes: 0