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

后端 未结 28 1094
感动是毒
感动是毒 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:45

    my approach, what i think is simple and has time complexity O(n).

    Step 1: First get the count of number of nodes. Run a for loop starting from first node to the last node

    Step 2: Once you have the count, apply simple math, for example if we have find 7th node to the last node and the count of all nodes is 12, then (count - index)- 1 will give some kth node, upto which you will have to traverse and it will be the nth node to the last node. In this case (12 -7)-1 = 4

    If the elements are 8->10->5->7->2->1->5->4->10->10 then the result is 7th to last node is 7, which is nothing but 4th node from the beginning.

提交回复
热议问题