问题
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 theKth
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 thehare
pointer, moves theturtle
.
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