在双向链表末尾插入节点

要在双向链表的插入节点,要分两种情况分别处理:链表是空的还是包含元素。 使用以下步骤以在双向链表的末尾插入节点。

  • 为新节点分配内存,使指针ptr指向要插入的新节点。
    ptr = (struct node *) malloc(sizeof(struct node));
    
  • 检查链表是否为空。如果条件head == NULL成立,则链表为空。 在这种情况下,节点将作为链表的唯一节点插入,因此节点的prevnext指针将指向NULL,并且head指针将指向此节点。

    ptr->next = NULL;  
    ptr->prev=NULL;  
    ptr->data=item;  
    head=ptr;
    
  • 在第二种情况下,条件head == NULL变为false。新节点将作为链表的最后一个节点插入。 为此,需要遍历整个链表才能到达链表的最后一个节点。 将指针temp初始化为head并使用此指针遍历链表。

    temp = head;   
    while (temp != NULL)  
    {  
      temp = temp -> next;   
    }
    

    指针temp指向此while循环结束时的最后一个节点。 现在,只需要做一些指针调整就可以将新节点ptr插入到链表中。 首先,使temp指针指向要插入的新节点,即ptr

temp->next =ptr;

使节点ptr的前一指针指向链表的现有最后一个节点,即temp

ptr -> prev = temp;

使节点ptrnext指针指向null,因为它将是链表新的最后一个节点。

ptr -> next = NULL

算法

第1步:IF PTR = NULL
  提示 OVERFLOW 
   转到第11步
  [IF结束]

第2步:设置NEW_NODE = PTR
第3步:SET PTR = PTR - > NEXT
第4步:设置NEW_NODE - > DATA = VAL
第5步:设置NEW_NODE - > NEXT = NULL
第6步:SET TEMP = START
第7步:在TEMP - > NEXT!= NULL 时重复第8步
第8步:SET TEMP = TEMP - > NEXT
[循环结束]

第9步:设置TEMP - > NEXT = NEW_NODE
第10步:SET NEW_NODE - > PREV = TEMP
第11步:退出

示意图 -

C语言示例代码 -

#include<stdio.h>  
#include<stdlib.h>  
void insertlast(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);
        insertlast(item);
        printf("Press 0 to insert more ?\n");
        scanf("%d", &choice);
    } while (choice == 0);
}
void insertlast(int item)
{

    struct node *ptr = (struct node *) malloc(sizeof(struct node));
    struct node *temp;
    if (ptr == NULL)
    {
        printf("OVERFLOW");

    }
    else
    {

        ptr->data = item;
        if (head == NULL)
        {
            ptr->next = NULL;
            ptr->prev = NULL;
            head = ptr;
        }
        else
        {
            temp = head;
            while (temp->next != NULL)
            {
                temp = temp->next;
            }
            temp->next = ptr;
            ptr->prev = temp;
            ptr->next = NULL;
        }
        printf("Node Inserted\n");

    }
}

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

Enter the item which you want to insert?
12

Node Inserted

Press 0 to insert more ?
2

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