刪除迴圈單鏈表末尾元素

在迴圈單鏈表中刪除末尾節點有三種情況。

情況1(鏈表為空)

如果鏈表為空,則條件head == NULL將變為true,在這種情況下,只需要在螢幕上列印下溢並退出。

if(head == NULL)
{
    printf("UNDERFLOW\n");
    return;
}

情況2(鏈表包含單個節點)

如果鏈表包含單個節點,則條件head->next == head將變為true。 在這種情況下,需要刪除整個鏈表並使頭指針空閒。 這將通過使用以下語句來完成。

if(head->next == head)
{
    head = NULL;
    free(head);
}

情況3(鏈表包含多個元素)

如果鏈表中有多個節點,那麼要刪除最後一個節點,需要到達最後一個節點。 還需要跟蹤鏈表的倒數第二個節點。 為此,需要定義兩個指針ptrpreptr。 以下代碼序列用於此目的。

ptr = head;
while(ptr ->next != head)
{
    preptr=ptr;
    ptr = ptr->next;
}

現在,需要再做一次指針調整。需要將指針指向pretrnext指向ptrnext(即head),然後使指針ptr空閒(釋放)。

preptr->next = ptr -> next;
free(ptr);

演算法

第1步:IF HEAD = NULL
   提示 “記憶體溢出”

    轉到第8步

   [IF結束]

第2步:設置PTR = HEAD
第3步:重複第4步和第5步,同時PTR - > NEXT!= HEAD
第4步:SET PREPTR = PTR
第5步:SET PTR = PTR - > NEXT
[迴圈結束]

第6步:設置PREPTR - > NEXT = HEAD
第7步:釋放PTR
第8步:退出

示意圖

C語言實現示例代碼 -

#include<stdio.h>
#include<stdlib.h>
void create(int);
void last_delete();
struct node
{
    int data;
    struct node *next;
};
struct node *head;
void main()
{
    int choice, item;
    do
    {
        printf("1.Append List\n2.Delete Node from end\n3.Exit\n4.Enter your choice?");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            printf("Enter the item\n");
            scanf("%d", &item);
            create(item);
            break;
        case 2:
            last_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));
    struct node *temp;
    if (ptr == NULL)
    {
        printf("OVERFLOW\n");
    }
    else
    {
        ptr->data = item;
        if (head == NULL)
        {
            head = ptr;
            ptr->next = head;
        }
        else
        {
            temp = head;
            while (temp->next != head)
                temp = temp->next;
            ptr->next = head;
            temp->next = ptr;
            head = ptr;
        }
        printf("Node Inserted\n");
    }

}
void last_delete()
{
    struct node *ptr, *preptr;
    if (head == NULL)
    {
        printf("UNDERFLOW\n");
    }
    else if (head->next == head)
    {
        head = NULL;
        free(head);
        printf("Node Deleted\n");
    }
    else
    {
        ptr = head;
        while (ptr->next != head)
        {
            preptr = ptr;
            ptr = ptr->next;
        }
        preptr->next = ptr->next;
        free(ptr);
        printf("Node Deleted\n");
    }
}

執行上面示例代碼,得到以下結果 -

1.Append List
2.Delete Node from end
3.Exit
4.Enter your choice?1

Enter the item
90

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

Node Deleted

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