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个节点"链表的
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
