Friday, June 22, 2012

Linked List Insert nth problem

A linked list problem for inserting a node after the nth index !!

InsertNth() Solution


void InsertNth(struct node** headRef, int index, int data)
if (index == 0)
   Push(headRef, data);                       // position 0 is a special case...
else {
  struct node* current = *headRef;
   int i;
     for (i=0; i<index-1; i++) {
     assert(current != NULL); // if this fails, index was too big
     current = current->next;
      }
Push(&(current->next), data);
}
}

No comments:

Post a Comment