返回链表中倒数第5个元素
return 5th element from last in linked list?
以上问题是我在面试中被问到的。虽然我还在等待结果,但我想知道我的方法是否正确,或者是否有更好的解决方案?
struct Node
{
int data;
Node * next;
};
Node *function( struct Node *head)
{
if ( ! head)
{
std::cout <<" no linked present";
return 0;
}
Node *current, *temp;
temp = NULL;
current = head;
int counter = 0;
while( current != NULL)
{
counter ++;
current = current->next;
if( counter >= 5)
{
if( temp == NULL)
temp = head;
else
temp = temp->next;
}
}
return (temp);
}
如果你们有更好的最佳解决方案,请贴在这里。谢谢大家山姆
对于单链表,您的解决方案应该是最优的。对于双链表,可以从后面开始。
如果您排除列表长度小于5个元素的情况,我会说下一个解决方案更优雅一些,但本质上是一样的:
Node *function( struct Node *head)
{
while ( head->next->next->next->next )
head = head->next;
return head
}
性能方面,对于单链表,您不能做得比O(n)
更好,所以所有可以改进的是可读性。
Vlad在注释中提出了一个有趣的观点,即在循环的每次迭代中执行更多的指令。我认为这是错误的,因为指针访问只需要1 asm指令。然而,在OP的代码中:
counter ++;
current = current->next;
if( counter >= 5)
{
if( temp == NULL)
temp = head;
else
temp = temp->next;
}
是在循环中执行的指令。这样效率就低多了。自增,2个指针赋值和2个比较…
都是O(n)
,但对于大输入,时间是4*n还是10*n很重要。
看起来会很好。唯一的问题是您没有在代码中声明temp,也没有将其初始化为NULL。
相关文章:
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 在C++中,如何通过几种类型从元组中选择多个元素
- 删除列表中的第n个元素
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 在链链表中手动插入第五个元素
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 高级选择排序 - 在一次迭代中搜索两个元素
- 删除列表 c++ 中的最后 3 个元素
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 打印无序映射的第二个元素,即集合
- C++ queue.front();为什么不从第一个元素开始呢?
- 正确unique_ptr 1 个元素分配数组的声明
- 指向数组基址的指针而不是指向第一个元素的指针有什么优点?
- 静态堆栈函数不会 1) 输入第一个元素 2)添加新元素时识别旧元素
- c++:交换向量中所有元组的第一个和第二个元素
- 从队列中删除第一个元素C++