<分区>
我有一个问题:
Find the middle element from a single linked list.
我需要知道这个问题的方式/方法。
<分区>
我有一个问题:
Find the middle element from a single linked list.
我需要知道这个问题的方式/方法。
最佳答案
您可以使用两个指针遍历列表 - 一个的迭代速度是另一个的两倍。当快指针到达列表的末尾时,慢指针将指向中间点。
算法:
init slow_pointer = head
init fast_pointer = head
repeat
fast_pointer = fast_pointer->next;
if fast_pointer == NULL
break;
fast_pointer = fast_pointer->next;
if fast_pointer == NULL
break;
slow_pointer = slow_pointer->next;
until false
// slow_pointer now points at the middle node
关于algorithm - 从单个链表中提取中间元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35653250/