在雙向鏈表末尾插入節點

要在雙向鏈表的插入節點,要分兩種情況分別處理:鏈表是空的還是包含元素。 使用以下步驟以在雙向鏈表的末尾插入節點。

  • 為新節點分配記憶體,使指針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

上一篇: 雙鏈表 下一篇: 迴圈單向鏈表