algorithm - 从单个链表中提取中间元素

标签 algorithm 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/

相关文章:

python - Python中的Powerset算法: difference between + and append on lists

c# - 使用 ReadByte() 读取泛型类型

java - 如何打印我的 LinkedList 中的条目?

linked-list - 查找链表中是否存在没有两个指针的循环

c++ - 删除单向链表的所有节点

c++ - 求和每个节点是一个数字的两个链表

java - 删除双向链表中的节点时出现问题

c# - 帮助创建计划生成器

algorithm - 为速度牺牲准确性的搜索/排序算法

algorithm - 更快的次优 MST 算法?