在双向链表中的元素之后插入

Insertion after a element in doubly linked list

我在链表中​​的一个元素之后插入元素,但我的代码不是 运行。

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;
}
   ptr->next=ptr1;
  ((ptr->next)->next)->prev=ptr1;

您正在更改新创建的指针 ptr1 旁边的 ptr。 ptr1 的 next 在这里显然是 null。你必须让它指向 ptr

的下一个节点
ptr1->next = ptr->next

然后你必须让ptr指向ptr1

ptr->next = ptr1

它将起作用,请 post 您在控制台中看到的错误。

你必须link新节点的下一个节点和新节点之前的节点。

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
    }