Search code examples
csingly-linked-listinsertion

How to insert new node in a singly linked list after nth position?


OKay, so I want to insert a new node in a singly linked list in C at the nth position(not end or beginning), but all I get after searching is that how to insert new nodes at beginning or end of a linked list. Any help is appreciated. Thanks.


Solution

  • something like this perhaps.

     void insert_at(list_node **list, list_node *new,int offset)
     {
         while(offset-- && (*list)->next )
            list=&((*list)->next);
         new->next=(*list)->next
         (*list)->next=new;
     }