从单链接列表(从尾部)中查找元素
Find element from singled linked list (from tail)
我有一个单身链接列表。
例如:52-> 79-> 67-> 50-> 16-> 99-> 75
如果我想从反向顺序获得第三个数字(应该是16个),我该怎么办?要求不允许我倒转列表。
唯一的提示是:有一种算法仅通过链接列表进行扫描一次!一种可能是使用两个指针扫描列表。
谁能帮我解决这个问题?
如果 k
是尾部的元素数,请创建两个指针:一个指向开始,另一个指向开始 k。同时增加两个。当第二个到达末端时,第一个是您的元素。
使用两个指针:
Node* kthFromEnd(int k, Node *first) {
Node *second = first;
// Advance first k-1 times
while(first && --k) {
first = first->next();
}
// Now second is k nodes behind first, go to the end
while(first) {
first = first->next();
second = second->next();
}
// First is at the end, second is still k nodes behind
return second;
}
如下
T *first = 0;
T *last = head;
size_t i = 0;
while ( i < N && last )
{
++i;
last = last->next;
}
if ( i == N )
{
first = head;
while ( tail )
{
++tail;
++first;
}
}
return first;
保持大小3的圆形阵列或更一般的尺寸k(对于kth-last元素)。
浏览列表,只需添加到数组。完成后,返回数组中的下一个元素。
其他答案中建议的两个指针。
示例输入:
52 -> 79 -> 67 -> 50 -> 16 -> 99 -> 75
数组看起来像:
[0, 0, 0]
[52, 0, 0]
[52, 79, 0]
[52, 79, 67]
[50, 79, 67]
[50, 16, 67]
[50, 16, 99]
[75, 16, 99]
然后返回下一个元素 -> 16
。
相关文章:
- 在对向量中查找元素的索引
- 在链接列表中查找元素 - C++
- 在数组中查找元素,如果找到则返回Find,否则返回not Find
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 用于查找元素的数据结构
- 为什么在查找元素时需要使用 set.find(x) != set.end()
- 在二叉搜索树中查找元素
- 二进制搜索不变以查找元素的首次出现
- 迭代列表以查找元素的出现.代码问题
- 从单链接列表(从尾部)中查找元素
- iMacro 查找元素
- 在向量数组中查找元素
- 如何在二叉搜索树中查找元素
- 如何在字符右侧的QString中查找元素
- 在Vector中查找元素对
- 如何在运行时在boost::fusion::vector中查找元素
- 在 stl 堆栈 cpp 中查找元素
- 在向量中查找元素并将其删除
- 如何在动态数组中查找元素的数量
- 在数组中查找元素,然后使用指针进行交换