How to find nth element from the end of a singly linked list?

后端 未结 28 1087
感动是毒
感动是毒 2020-12-04 06:08

The following function is trying to find the nth to last element of a singly linked list.

For example:

If the elements are

28条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 06:39

    Depending of the memory cost tolerance (O(k) in this solution) we could allocate an array of pointers of length k, and populate it with the nodes as a circular array while traversing the linked list.

    When we finish traversing the linked list, the first element of the array (just be sure to calculate the 0-index properly as it's a circular array) we'll have the answer.

    If the first element of the array is null, there's no solution to our problem.

提交回复
热议问题