我目前正在学习 Cambridge Book of dataStructures,每次我想到一个问题时,在看到解决方案之前,我都会尝试解决它。
我在使用 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;
}
}
我的代码有什么问题?谢谢大家!
最佳答案
考虑循环条件:
while (runner != end)
在循环结束时,runner
等于end
。因此,您基本上是将 end.Next
设置为 null
并将 end
设置为其自身。
您需要到达 end
节点之前的节点。
将循环条件更改为:
while (runner.Next != end)
这将确保在循环结束时,runner
将是恰好在 end
节点之前的节点。
另请注意,此代码不处理 start
等于 end
的情况(当链表仅包含一个节点时)。
关于C# 使用 base 中的链表数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36680812/