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

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

    Here is the code using 2 pointer approach : ( source )

    Slow and Faster pointer approach

    struct node
    {
      int data;
      struct node *next;
    }mynode;
    
    
    mynode * nthNodeFrmEnd(mynode *head, int n /*pass 0 for last node*/)
    {
      mynode *ptr1,*ptr2;
      int count;
    
      if(!head)
      {
        return(NULL);
      }
    
      ptr1  = head;
      ptr2  = head;
      count = 0;
    
      while(count < n)
      {
         count++;
         if((ptr1=ptr1->next)==NULL)
         {
            //Length of the linked list less than n. Error.
            return(NULL);
         }
      }
    
      while((ptr1=ptr1->next)!=NULL)
      {
        ptr2=ptr2->next;
      }
    
      return(ptr2);
    }
    


    Recursion

    node* findNthNode (node* head, int find, int& found){
        if(!head) {
            found = 1;
            return 0;
        }
        node* retval = findNthNode(head->next, find, found);
        if(found==find)
            retval = head;
        found = found + 1;
        return retval;
    }
    

提交回复
热议问题