问题
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
harepointer at the start of the list - Move it at least
Kelements away - If you hit the
lastelement before, then you cannot find theKthto last element. - Place a
turtlepointer at the start of the list - Now runs the
harepointer to the end of the list, each time you move theharepointer, 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