简体   繁体   中英

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.

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;
 }

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;
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM