查找链接列表的中间元素

时间:2018-08-09 14:00:03

标签: c# algorithm data-structures

我们有一个'n'个元素的链表。如何找到中间元素?

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

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

3 个答案:

答案 0 :(得分:2)

是的,您的代码是正确的。下面是使用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 //,您可以根据需要进行修改。

答案 1 :(得分:0)

实现:

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

答案 2 :(得分:0)

这是一个简化的算法:

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

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

相关问题