Implement an algorithm to find the kth to last element of a singly linked list

岁酱吖の 提交于 2019-12-24 17:13:38

问题


Implement an algorithm to find the kth to last element of a singly linked list.

Is a good solution to the above problem, reversing the linked list then traversing again and getting the kth element?


回答1:


First of all the list is singly-linked. So that is a good hint that you should not try to reverse it, because you would need as much storage to make the copy.

You can use a modified version of the turtle-hare algorithm:

  • Use a hare pointer at the start of the list
  • Move it at least K elements away
  • If you hit the last element before, then you cannot find the Kth to last element.
  • Place a turtle pointer at the start of the list
  • Now runs the hare pointer to the end of the list, each time you move the hare pointer, moves the turtle.

When the hare pointer reach the end of the list, the turtle is on the Kth to last element.



来源:https://stackoverflow.com/questions/32507486/implement-an-algorithm-to-find-the-kth-to-last-element-of-a-singly-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!