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

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

    Recursive solution:

    Node findKth (Node head, int count, int k) {
        if(head == null)
            return head;
        else {
            Node n =findKth(head.next,count,k);
            count++;
    
            if(count == k)
                return head;
    
            return n;
        }
    }
    

提交回复
热议问题