在单个链接列表中找到最后一个K

发布于 2025-02-04 02:53:40 字数 478 浏览 3 评论 0原文

有一个算法,该算法应采用输入k并返回相应的k-th最后元素,因此,如果k = 1,则应返回最后一个元素,如果k = 2,如果应该返回第二个元素...等等

我 我不了解某些代码在做什么,或者为什么需要在那里,例如:

n = n - k + 1

这是整个代码,任何帮助理解每行正在做的事情的帮助都很棒:

function lastk(List L, Int k) → List 
  tmp = L
  n = 0
  while tmp ̸= NIL do
    n=n+1
    tmp = tmp.next 
  if n<k then
    return NIL 
  else
    tmp = L
    n = n − k + 1 
    i=1
    while i < n do
      tmp = tmp.next
      i=i+1 
    return tmp

I have an algorithm that should take input k and return the corresponding k-th last element, so if k=1, it should return the last element, if k=2 if should return the second last element...and so on

I am not understanding what some of the lines of code are doing or why they need to be there such as:

n = n - k + 1

this is the entire code, any help understanding what each line is doing would be great:

function lastk(List L, Int k) → List 
  tmp = L
  n = 0
  while tmp ̸= NIL do
    n=n+1
    tmp = tmp.next 
  if n<k then
    return NIL 
  else
    tmp = L
    n = n − k + 1 
    i=1
    while i < n do
      tmp = tmp.next
      i=i+1 
    return tmp

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宁愿没拥抱 2025-02-11 02:53:40

首先, 循环计算列表的长度l返回nil如果此长度小于k

接下来的两行否则tmp = l是多余的。

n-k + 1k - the元素的索引。

第二个 循环将列表遍历到此元素。

First while loop calculates the length of the list L returns NIL if this length is less than k.

Next two lines else tmp = L are redundant.

n − k + 1 is the index of the k-th element from the end.

Second while loop traverses the list to this element.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文