Write a program to insert a node at a given position in a single linked list?

Showing Answers 1 - 12 of 12 Answers

ilushka

  • Nov 3rd, 2011
 

Something like this:

Code
  1. // llist - linked list into which node will be inserted

  2. // node - linked list node to be inserted

  3. // pos - zero-based position within the linked list

  4.  

  5. void insert_node(node_t *llist, node_t *node, int pos) {

  6.   node *prev, *next = llist;

  7.  

  8.   while (pos && next) {

  9.     prev = next;

  10.     next = next->next;

  11.   }

  12.  

  13.   node->next = next;

  14.   if (prev) {

  15.     prev->next = node;

  16.   }

  17. }

  Was this answer useful?  Yes

ptmich

  • May 28th, 2012
 

Code
  1. void insert_node(node_t *llist, node_t *node, int pos) {

  2. llist.insertNodeAt(node);

  3. return llist;

  4.  }


  Was this answer useful?  Yes

Rahul goyal

  • Jul 20th, 2012
 

Code
  1. //let the structure name be stud

  2. void insert_pos(stud *head, pos)

  3. {

  4.   stud s,*t;

  5.  s.input(); //accept the data

  6.  t=head;

  7. pos--;

  8. while(t!=NULL && pos)

  9. {

  10.   t=t->next;

  11.    pos--;

  12. }

  13. s->next=t->next;

  14. t->next=s;

  15. }

  16.  



rjshkr

  • Sep 28th, 2012
 

Code
  1.  NODE insert(NODE head,int data,int pos)

  2. {

  3.         NODE temp,new,prev = NULL;

  4.         int i=1;

  5.         new = (NODE)malloc(sizeof(struct node));

  6.         new->info = data;

  7.         if(head == NULL)

  8.         {

  9.                 new->link = NULL;

  10.                 return new;

  11.         }

  12.         if(pos==1)

  13.         {

  14.                 new->link = head;

  15.                 return new;

  16.         }

  17.         temp = head;

  18.         while(temp != NULL && i<pos)

  19.         {

  20.                 prev = temp;

  21.                 temp = temp->link;

  22.                 i++;

  23.         }

  24.         if(temp == NULL)

  25.         {       prev->link = new;

  26.                 new->link = NULL;

  27.         }

  28.         else

  29.         {

  30.                 prev->link = new;

  31.                 new->link = temp;

  32.         }

  33.         return head;

  34. }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions