-1

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.

David Buck
  • 3,752
  • 35
  • 31
  • 35
Anony Mous
  • 23
  • 2

3 Answers3

3

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;
 }
Jasen
  • 11,837
  • 2
  • 30
  • 48
1

This will work:

void InsertNode(int position, int newdata)

{
    struct Node* temp = (struct Node* )malloc(sizeof(struct Node* ));
    temp->data=newdata;    
    struct Node* temp2=head;
    
    if(position==1)
    {
        temp->next=temp2;
        head=temp;
        return ;
    }
        
    for(int i=1;i<position;i++)
    {
        temp2=temp2->next;
    }

    temp->next=temp2->next;
    temp2->next=temp;
    return;
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
Nick Rock
  • 29
  • 4
0

I have found the solution myself. This is my algorithm -

Step 1- given a linked list, index it.

Step 2- Ask for the index after which the user wants to insert the new node

Step 3- Traverse though the linked list until you have reached that index

Step 4- Make a new node which points to the node after the current index

Step 5- Make the node of the index inputted by the user point to the new node

Voila, done!

Anony Mous
  • 23
  • 2