<分区>
我们有一个包含“n”个元素的链表。我怎样才能找到中间元素?
我可以这样做吗? (这是一个伪代码)
Node current = head;
for (int i = 0; i < n/2; i++)
{
current = current.next;
}
return current;
<分区>
我们有一个包含“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/