c# - 查找链表的中间元素

标签 c# algorithm data-structures

<分区>

我们有一个包含“n”个元素的链表。我怎样才能找到中间元素?

我可以这样做吗? (这是一个伪代码)

Node current = head;
for (int i = 0; i < n/2; i++)
{
    current = current.next;
}
return current;

最佳答案

是的,您的代码是正确的。下面是另一种使用龟兔赛跑算法的方法。

if(head == null) return head;
if(head.next == null || head.next.next == null) return head;


Node slow = head,fast = head.next.next;

while(fast != null && fast.next != null){
    slow = slow.next;
    fast = fast.next.next;
}


if(fast != null) slow = slow.next;

Console.writeLine(slow.data);
  • 如果列表是 [1,2,3,4,5,6,7] => 这将返回 4

    <
  • 如果列表是 [1,2,3,4,5,6] => 这将返回 3。//如果您希望可以返回4 略作修改。

  • 如果列出 [1][1,2] => 它返回 1//你可以再次修改它根据您的需要。

关于c# - 查找链表的中间元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51769029/

相关文章:

c# - 在数据集中查找外键

algorithm - 如何找到树中两个节点之间路径中最重边的权重?

c++ - 排序算法中的递归 - 总是不好?

php - 比在多维数组上迭代搜索以找到对应值更好的数据结构或算法?

Java简单链表

c - 如何用C语言将树数据写入文件?

c# - Autofac 模块缺少准备事件

c# - Windows 安装程序禁止某些安装位置

c# - 如何使用 C# 表单应用程序将 pdf、xls 等文件添加/插入到 mysql 数据库

c - BASH/CSH/ZSH 样式大括号扩展算法