刪除雙連結串列開頭節點

2019-10-16 22:03:10

刪除雙向連結串列中的第一個節點是最簡單的操作。只需要將頭指標複製到指標ptr並將頭指標移動到下一個指標。

ptr = head;  
head = head -> next;

現在使這個新頭節點的prev指標指向NULL。這將通過使用以下語句來完成。

head -> prev = NULL;

現在使用free函式釋放指標ptr

free(ptr);

演算法

第1步:如果HEAD = NULL
    提示 記憶體溢位。
    轉到第6步
第2步:設定PTR = HEAD
第3步:設定HEAD = HEAD->NEXT
第4步:設定HEAD->PREV = NULL
第5步:釋放PTR
第6步:退出

示意圖

C語言實現範例程式碼 -

#include<stdio.h>  
#include<stdlib.h>  
void create(int);
void beginning_delete();
struct node
{
    int data;
    struct node *next;
    struct node *prev;
};
struct node *head;
void main()
{
    int choice, item;
    do
    {
        printf("1.Append List\n");
        printf("2.Delete node from beginning\n");
        printf("3.Exit\n");
        printf("4.Enter your choice ? ");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            printf("Enter the item\n");
            scanf("%d", &item);
            create(item);
            break;
        case 2:
            beginning_delete();
            break;
        case 3:
            exit(0);
            break;
        default:
            printf("Please enter valid choice\n");
        }

    } while (choice != 3);
}
void create(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;printf("Press 0 to insert more ?\n");
            ptr->prev = NULL;
            ptr->next = head;
            head->prev = ptr;
            head = ptr;
        }
        printf("Node Inserted\n");
    }

}
void beginning_delete()
{
    struct node *ptr;
    if (head == NULL)
    {
        printf("UNDERFLOW\n");
    }
    else if (head->next == NULL)
    {
        head = NULL;
        free(head);
        printf("Node Deleted\n");
    }
    else
    {
        ptr = head;
        head = head->next;
        head->prev = NULL;
        free(ptr);
        printf("Node Deleted\n");
    }
}

執行上面範例程式碼,得到以下結果 -

1.Append List
2.Delete node from beginning
3.Exit
4.Enter your choice?1

Enter the item
12

Node Inserted
1.Append List
2.Delete node from beginning
3.Exit
4.Enter your choice?2

Node Deleted
1.Append List
2.Delete node from beginning
3.Exit
4.Enter your choice?