Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 查找链表的中间元素_C#_Algorithm_Data Structures - Fatal编程技术网

C# 查找链表的中间元素

C# 查找链表的中间元素,c#,algorithm,data-structures,C#,Algorithm,Data Structures,我们有一个“n”元素的链接列表。如何找到中间元素 我可以这样做吗?(这是一个伪代码) 节点电流=头部; 对于(int i=0;i则返回4 如果列表为[1,2,3,4,5,6]=>则返回3//如果您愿意,可以通过轻微修改返回4 如果列表[1]或[1,2]=>返回1//您也可以根据需要修改此列表 我认为不能通过c#中的索引访问LinkedList中的元素,因为这是一个链接列表,所以这个答案不起作用。您不能通过访问元素index@Oerk谢谢你的邀请comments@ThierryV你是welcome

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

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

节点电流=头部;
对于(int i=0;i
简化:

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

下面是一个简化的算法:

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

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

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

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#中的索引访问LinkedList中的元素,因为这是一个链接列表,所以这个答案不起作用。您不能通过访问元素index@Oerk谢谢你的邀请comments@ThierryV你是welcome@ThierryV你仍然有错误的括号。为什么不试试,看看它是否有效,如果无效,然后回来问一个关于真实代码的问题?通常在问这个问题时,您不能假设您有
n
作为参数。谢谢您的评论。我知道这个解决方案,但我想知道我的问题是对的还是错的?“如果是错的,为什么?”乔更新了我的answer@Joe欢迎:)@Joe虽然您的代码是正确的,但vivek的代码有一个好处,即事先不知道链接列表的长度。
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);