【问题标题】:Find middle element of Linked List [duplicate]查找链表的中间元素[重复]
【发布时间】:2018-08-09 14:00:02
【问题描述】:

我们有一个包含“n”个元素的链接列表。如何找到中间元素?

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

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

【问题讨论】:

  • 为什么不试试看它是否有效,如果无效,然后再回来询问有关真实代码的问题?
  • 通常当被问到这个问题时,你不能假设你有n作为参数。

标签: c# algorithm data-structures


【解决方案1】:

是的,您的代码是正确的。下面是使用 Tortoise and Hare 算法的另一种方法。

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// 再次您可以根据需要进行修改。

【讨论】:

  • 感谢您的评论。我知道那个解决方案,但我想知道我的问题是对还是错?如果是错的,为什么?
  • @Joe,更新了我的答案
  • @Joe 欢迎 :)
  • @Joe 虽然您的代码是正确的,但 vivek 的代码的好处是事先不知道链表的长度。
【解决方案2】:

这是一个简化的算法:

var enumerator1 = linked.GetEnumerator();
var enumerator2 = linked.GetEnumerator();
int count = 0;
while (enumerator1.MoveNext())
{
    count++;
    if (count % 2 == 0)
        enumerator2.MoveNext();
}

主指针每移动两次,第二个指针移动一次。

【讨论】:

    【解决方案3】:

    简单:

    var current = list.ElementAt(list.Count()/2);
    

    【讨论】:

    • 我认为你不能通过 c# 中的索引访问 LinkedList 中的元素
    • 因为这是一个链表,所以这个答案是行不通的。你不能通过索引访问元素
    • @Oerk 感谢 cmets
    • @ThierryV 不客气
    • @ThierryV 你的括号还是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2014-04-21
    • 2019-12-31
    • 2021-12-04
    • 1970-01-01
    • 2010-10-10
    相关资源
    最近更新 更多