ProAnswers.org

algorithm Insert a node in a linked list

algorithm Insert a node in a linked list

typedef struct node{

	    int data;

	    struct node *next;

	}node;

	 

	/*This function inserts a node a given index

	  in a linked list pointed by head pointer */

	 

	node *insert(node *head, int elem, int index){

	    node *insert, *move;

	    int i;

	    move = head;

	    insert = (node *)malloc(sizeof(node));

	    insert->data = elem;

	    if(index == 1){

	        //insert at the beginning of the list

	        insert->next = head;

	        head = insert;

	        return head;

	    }

	    if(index == (count_list(head)+1)){

	    //insert at end of the list

	        for(;move->next != NULL; move = move->next);

	        move->next = insert;

	        insert->next = NULL;

	        return head;

	    }

	    else{         //insert at index i

	    for(i = 1; i < index-1; i++, move = move->next);

	    insert->next = move->next;

	    move->next = insert;

	    return head;

	   }

	}