在单个链接列表中找到最后一个K
有一个算法,该算法应采用输入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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先, 循环计算列表的长度
l
返回nil
如果此长度小于k
。接下来的两行
否则tmp = l
是多余的。n-k + 1
是k
- the元素的索引。第二个 循环将列表遍历到此元素。
First
while
loop calculates the length of the listL
returnsNIL
if this length is less thank
.Next two lines
else tmp = L
are redundant.n − k + 1
is the index of thek
-th element from the end.Second
while
loop traverses the list to this element.