Find nth node from end of a singly linked list

Questions by smart_coder   answers by smart_coder

Showing Answers 1 - 3 of 3 Answers

Abi George Ullattil

  • Feb 9th, 2007
 

struct node{ int data; node* next;};// This function will return the point to the nth node from the end.// If the number of links is less the value n, then it returns the start of the linked list// If the linked list has only one node, then it returns the link to the end node// (which again is the start node for that linked list)node* findNthNodeFromEnd(node *end,int n){ if(!end || n<0) return NULL; else if(n == 0) return end; char *p; node *curr,*prev = end; int i = 0; curr = prev - 1; p = (char*)curr; while(p != 0) { if(curr->next == prev) { ++i; if(i == n) return curr; prev = curr; } --p; curr = (node*)p; } return prev;}The explanation for this one should be easily understandable i guess. If you have doubt mail me.

  Was this answer useful?  Yes

Apoorv

  • Feb 16th, 2007
 

A simple way out would be..Use two pointers..*traverse and *nth_positionboth initialised to null..While you traverse to the end of the list using *traverse,let *nth_position follow only after n iterations..So at all times, *nth_position will be n places behind *traverse..Continue till traverse reaches end of list..If list has less than n nodes, nth_position points to null.

j_l_larson

  • Oct 19th, 2009
 

node*GetNthFromEnd(node* pHead, int n) {
    if ( ! pHead )
      return NULL;
    int i = 0;
    node* p = pHead;
    node* pnth = pHead;
    while (p) {
      if ( i++ >= n ) {
        pnth = pnth->GetNext();
      }
      node* pNext = p->GetNext();
      p = pNext;
    }
    if ( i < n )
      return NULL;
    return pnth;
  }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions