C#使用baseList中的LinkedList DataStructure

时间:2016-04-17 18:54:39

标签: c# algorithm data-structures linked-list nodes

我目前正在学习剑桥数据结构书,每当我想到问题时,在我看到解决方案之前,我都试图解决它。 我遇到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;
             }
        }

我的代码有什么问题?大家好!

1 个答案:

答案 0 :(得分:1)

考虑循环条件:

while (runner != end)

在循环结束时,runner等于end。因此,您基本上将end.Next设置为null并将end设置为自己。

您需要在end节点之前到达节点。

将循环条件更改为:

while (runner.Next != end)

这将确保在循环结束时,runner将成为end节点之前的节点。

请注意,此代码不处理start等于end的情况(当链接列表只包含一个节点时)。