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

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

    //this  is the recursive solution
    
    
    //initial call
    find(HEAD,k);
    
    // main function
    void find(struct link *temp,int k)
    {  
     if( temp->next != NULL)
       find( temp->next, k);
     if((c++) == k)       // c is initially declared as 1 and k is the node to find from last.
      cout<num<<' ';
    }
    

提交回复
热议问题