Reputation: 63
It's supposed to take the last element out of a pseudo-LinkedList. The instructions suggested using a while loop to find the next-to-last element.
public String removeFromEnd() {
String removed = null;
if (head == null) {
return removed;
} else if (head.getNext() == null) {
removed = head.getName();
head = null;
} else if (head.getNext().getNext() == null) {
removed = head.getNext().getName();
head.setNext(null);
}
return removed;
}
Past attempts usually look similar to this:
public String removeFromEnd() {
String removed = null;
while (head.getNext().getNext() == null){
removed = head.getNext().getName();
head.setNext(null);
}
if (head.getNext() == null){
removed = head.getName();
head = null;
}
return removed;
}
Upvotes: 2
Views: 704
Reputation: 163
// Java Code
public String removeFromEnd() {
String removed = null;
Node prev = null;
Node node = head;
while(node != null && node.getNext() != null)
{
prev = node;
node = node.getNext();
}
//the while loop should move the node to the end of the list
if(node != null)
{
removed = node.getName();
node = prev;
node.getNext().removeNode();
node.setNext(null);
}
return removed;
}
Upvotes: 1
Reputation: 25269
Node node = head;
Node prev = null;
while (node != null && node.getNext() != null) {
prev = node;
node = node.getNext();
}
Upvotes: 2
Reputation: 198033
In your attempt code...
while (head.getNext().getNext() == null){
removed = head.getNext().getName();
head.setNext(null);
}
You'll only enter this loop when head
is already the second-to-last element. You want to loop until head
is the second-to-last element. Does that help at all?
Upvotes: 1