0

I am inserting elements after a element in a linked list but my code is not running.

typedef struct Node
{
    int info;
    struct Node *next;
    struct Node *prev;
}node;

node *head;


// w-the element to be inserted & z-the position after which it has to inserted

void insertpos(int w,int z)
{
    int i;
    node *ptr=head;
    node *ptr1;
    for(i=1;i<=z-1;i++)
    {
        ptr=ptr->next;
    }
    ptr1=(node*)malloc(sizeof(node));
    ptr1->info=w;
    ptr->next=ptr1;
    ((ptr->next)->next)->prev=ptr1;
}
CiaPan
  • 9,381
  • 2
  • 21
  • 35
Newbie786
  • 43
  • 1
  • 7

2 Answers2

1
   ptr->next=ptr1;
  ((ptr->next)->next)->prev=ptr1;

You are changing the ptr next to newly created pointer ptr1. ptr1's next is obviously null here. You have to make it to point to next node of ptr

ptr1->next = ptr->next

Then you have to make ptr to point ptr1

ptr->next = ptr1

It will work and please post the error you see in the console.

Gibbs
  • 21,904
  • 13
  • 74
  • 138
  • The error is code is simply not running,it is asking to enter input again and again and then terminating after entering multiple input – Newbie786 Mar 19 '15 at 11:18
  • Then problem with your main function. Post your main function also – Gibbs Mar 19 '15 at 11:22
0

you have to link new node's next node and node previous to new node.

void insertpos(int w,int z)
       {
         int i;
         node *ptr=head;
         node *ptr1;
         for(i=1;i<=z-1;i++)
           {
           ptr=ptr->next;
           }
       ptr1=(node*)malloc(sizeof(node));
       ptr1->info=w;
       ptr1->next=ptr->next->next; //linking new node *next pointer
       ptr->next->next->prev=ptr1; //linking next node *prev to new node
       ptr->next=ptr1;  //ptr *next to new node
       ptr1->prev=ptr;  //new node *prev to previous node
    }
GorvGoyl
  • 42,508
  • 29
  • 229
  • 225