在双向链表开头插入节点

在双向链表中每个节点都包含两个指针,因此与单链表相比,在双链表中保存有更多的指针。

将任何元素插入双向链表有两种情况。 链表为空或包含至少一个元素。 执行以下步骤以在双向链表的开头插入节点。

  • 在内存中为新节点分配空间。这将通过使用以下语句来完成。
ptr = (struct node *)malloc(sizeof(struct node));
  • 检查链表是否为空。 如果条件head == NULL成立,则链表为空。 在这种情况下,节点将作为链表的唯一节点插入,因此节点的prevnext指针将指向NULL,并且头指针将指向此节点。
    ptr->next = NULL;  
    ptr->prev=NULL;  
    ptr->data=item;  
    head=ptr;
    
  • 在第二种情况下,条件head == NULL变为false,节点将在开头插入。 节点的下一个指针将指向节点的现有头指针。 现有headprev指针将指向要插入的新节点。这将通过使用以下语句来完成。
    ptr->next = head;  
    head->prev=ptr;
    

因为,插入的节点是链表的第一个节点,因此它的prev指针指向NULL。 因此,为其前一部分指定null并使头指向此节点。

ptr->prev = NULL;  
head = ptr;

算法

第1步:IF ptr = NULL
   提示 “OVERFLOW” 信息
  转到第9步
  [结束]

第2步:设置 NEW_NODE = ptr
第3步:SET ptr = ptr - > NEXT
第4步:设置 NEW_NODE - > DATA = VAL
第5步:设置 NEW_NODE - > PREV = NULL
第6步:设置 NEW_NODE - > NEXT = START
第7步:SET head - > PREV = NEW_NODE
第8步:SET head = NEW_NODE
第9步:退出

示意图

C语言实现示例 -

#include<stdio.h>  
#include<stdlib.h>  
void insertbeginning(int);
struct node
{
    int data;
    struct node *next;
    struct node *prev;
};
struct node *head;
void main()
{
    int choice, item;
    do
    {
        printf("Enter the item which you want to insert?\n");
        scanf("%d", &item);
        insertbeginning(item);
        printf("Press 0 to insert more ?\n");
        scanf("%d", &choice);
    } while (choice == 0);
}
void insertbeginning(int item)
{

    struct node *ptr = (struct node *)malloc(sizeof(struct node));
    if (ptr == NULL)
    {
        printf("OVERFLOW\n");
    }
    else
    {
        if (head == NULL)
        {
            ptr->next = NULL;
            ptr->prev = NULL;
            ptr->data = item;
            head = ptr;
        }
        else
        {
            ptr->data = item;
            ptr->prev = NULL;
            ptr->next = head;
            head->prev = ptr;
            head = ptr;
        }
    }

}

执行上面示例代码,得到以下结果 -

Enter the item which you want to insert?
12

Press 0 to insert more ?
0

Enter the item which you want to insert?
23

Press 0 to insert more ?
2

上一篇: 双链表 下一篇: 循环单向链表