1

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!

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.