Finding the quot;Nth node from the endquot; of a linked list(寻找“从末端开始的第N个节点链表的)
问题描述
这似乎返回了正确答案,但我不确定这是否真的是解决问题的最佳方式.好像我访问了前 n 个节点太多次了.有什么建议?请注意,我必须使用单向链表来执行此操作.
This seems to be returning the correct answer, but I'm not sure if this is really the best way to go about things. It seems like I'm visiting the first n nodes too many times. Any suggestions? Note that I have to do this with a singly linked list.
Node *findNodeFromLast( Node *head, int n )
{
Node *currentNode;
Node *behindCurrent;
currentNode = head;
for( int i = 0; i < n; i++ ) {
if( currentNode->next ) {
currentNode = currentNode->next;
} else {
return NULL;
}
}
behindCurrent = head;
while( currentNode->next ) {
currentNode = currentNode->next;
behindCurrent = behindCurrent->next;
}
return behindCurrent;
}
推荐答案
另一种无需两次访问节点的方法如下:
Another way to do it without visiting nodes twice is as follows:
创建一个大小为 n 的空数组,从索引 0 开始指向该数组的指针,并从链表的开头开始迭代.每次访问一个节点时,将其存储在数组的当前索引中并推进数组指针.当您填充数组时,环绕并覆盖您之前存储的元素.当您到达列表末尾时,指针将指向列表末尾的第 n 个元素.
Create an empty array of size n, a pointer into this array starting at index 0, and start iterating from the beginning of the linked list. Every time you visit a node store it in the current index of the array and advance the array pointer. When you fill the array, wrap around and overwrite the elements you stored before. When you reach the end of the list, the pointer will be pointing at the element n from the end of the list.
但这也只是一个 O(n) 算法.你目前正在做的很好.我看不出有什么令人信服的理由来改变它.
But this also is just an O(n) algorithm. What you are currently doing is fine. I see no compelling reason to change it.
这篇关于寻找“从末端开始的第N个节点"链表的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:寻找“从末端开始的第N个节点"链表的
基础教程推荐
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
