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]
这篇关于如何在单次遍历中找到单个链表的中间节点(如果没有给出链表的长度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在单次遍历中找到单个链表的中间节点(如果没有给出链表的长度)
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
