How to find the middle node of a single linked list in a single traversal (if the length of the list is not given)(如何在单次遍历中找到单个链表的中间节点(如果没有给出链表的长度))
问题描述
我有一个问题陈述,如:如何仅在一次遍历中找到单向链表的中间节点,而问题是我们不知道链表中的节点数?"
I have a problem statement like: "How to find the middle node of a singly linked list in only one traversal, and the twist is we don't know the number of nodes in the linked list?"
我有一个答案,比如当你遍历链表并增加一个计数器直到你到达链表的末尾时,取一个向量并开始推送所有节点的地址".所以最后我们可以得到列表中的节点数,如果偶数 (counter/2) 或奇数 (counter/2 + counter%2) 给出中间节点数,我们就可以得到 vectore.at(middlenodenumber) 指向中间节点".
I have an answer like "take a vector and start pushing all the nodes' addresses as and when you are traversing the linked list and increment a counter till you reach the end of the list". So at the end we can get the number of nodes in the list and if even (counter/2) or if odd (counter/2 + counter%2) gives the middle node number and with this we can get vectore.at(middlenodenumber) points to the middle node".
这很好……但是这是浪费内存来存储一个非常大的链表的所有地址!那么我们怎样才能有更好的解决方案呢?
This is fine...but this is waste of memory storing all the address of a very large linked list! So how can we have a better solution?
推荐答案
以下是步骤:
- 取两个指针
*p1和*p2指向链接的头部列表 - 开始循环并递增
*p2,2 次(带空检查) - 如果
*p2不为空,则将*p1增加 1 次 - 当
*p2达到空值时;你有*p1在中心
- Take two pointers
*p1and*p2pointing to the head of linked list - Start a loop and increment
*p2, 2 times (with null checks) - If
*p2is not null then increment*p11 time - When
*p2reaches null; you have got the*p1at the center
[注意:如果处理容器类型链表,可以使用迭代器代替指针]
[Note: You can use iterators instead of pointer if you deal with container type linked list]
这篇关于如何在单次遍历中找到单个链表的中间节点(如果没有给出链表的长度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在单次遍历中找到单个链表的中间节点(如果没有给出链表的长度)
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
