Reputation: 227
I'm currently learning Cambridge Book of dataStructures and each time I think about a problem, before I see the solution, I'm trying to solve it.
I'm Having a problem with RemoveLast()
public void RemoveLast()
{
if (end != null)
{
Node runner = start; //if end != null then start is initialized.
while (runner != end)
{
runner = runner.Next;
}
runner.Next = null;
end = runner;
}
}
What is the problem in my code? Thx guys!
Upvotes: 1
Views: 43
Reputation: 27861
Consider the loop condition:
while (runner != end)
At the end of the loop, runner
is equal to end
. So you are basically setting end.Next
to null
and setting end
to itself.
You need to get to the node right before the end
node.
Change the loop condition to this:
while (runner.Next != end)
This will make sure that at the end of the loop, runner
will be the node exactly before the end
node.
Please note also that this code does not handle the case where start
is equal to end
(when the linked list contains exactly one node).
Upvotes: 1