从单链接列表(从尾部)中查找元素

Find element from singled linked list (from tail)

本文关键字:查找 元素 尾部 列表 链接 单链接      更新时间:2023-10-16

我有一个单身链接列表。

例如: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