C# 使用 base 中的链表数据结构

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

我目前正在学习 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/

相关文章:

c# - 全局 vs 依赖注入(inject)

c# - Linq 查询 : Sum of columns for a given row

python - 二值(像素化)图像中的基本模式识别

python - 通过仅获取元组的第一个值来重新格式化元组列表时出现问题?

c++ - 动态数组的时间复杂度

c# - c# - web api中 "$"关键字的用途是什么

c# - Redis使用的数据结构

algorithm - 在 25 GB 的语料库中搜索单个单词

javascript - 如何调整网格中 "full bleed"的图像大小?

c++ - 多线程访问的高效结构