在單鏈表最後插入節點

要在單鏈表的最後插入節點,需要提及以下兩種情況。

  • 新節點添加到空鏈表中
  • 新節點添加到鏈表的末尾

1. 新節點添加到空鏈表中

如果滿足條件(head == NULL)。 因此,只需要在C語言中使用malloc語句為新節點分配空間。數據和節點的鏈接部分通過使用以下語句來設置。

ptr->data = item;
ptr -> next = NULL;

因為,ptr是插入鏈表中的唯一節點,因此需要使鏈表的頭指針指向這個新節點,通過使用以下語句來完成。

Head = ptr

2. 新節點添加到鏈表的末尾

如果條件head = NULL失敗,因為head不為null。需要聲明一個臨時指針temp才能遍曆鏈表。temp指向鏈表的第一個節點。

temp = head

然後,使用以下語句遍曆整個鏈表:

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

在迴圈結束時,temp將指向鏈表的最後一個節點。 現在,為新節點分配空間,並將專案分配給其數據部分。 因為,新節點將成為鏈表的最後一個節點,因此新節點下一鏈接部分需要指向null。 使temp節點的下一鏈接部分(當前是鏈表的最後一個節點)指向新節點(ptr)。

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

演算法

第1步:IF PTR = NULL
寫OVERFLOW
    轉到第1步

   [結束]

第2步:設置NEW_NODE = PTR
第3步:SET PTR = PTR - > NEXT
第4步:設置NEW_NODE - > DATA = VAL
第5步:設置NEW_NODE - > NEXT = NULL
第6步:設置PTR = HEAD
第7步:重複第8步,同時PTR - > NEXT != NULL
第8步:SET PTR = PTR - > NEXT
[迴圈結束]

第9步:SET PTR - > NEXT = NEW_NODE
第10步:退出

C語言示例代碼 -

#include<stdio.h>
#include<stdlib.h>
void lastinsert(int);
struct node
{
    int data;
    struct node *next;
};
struct node *head;
void main()
{
    int choice, item;
    do
    {
        printf("\nEnter the item which you want to insert?\n");
        scanf("%d", &item);
        lastinsert(item);
        printf("\nPress 0 to insert more ?\n");
        scanf("%d", &choice);
    } while (choice == 0);
}
void lastinsert(int item)
{
    struct node *ptr = (struct node*)malloc(sizeof(struct node));
    struct node *temp;
    if (ptr == NULL)
    {
        printf("\nOVERFLOW");
    }
    else
    {
        ptr->data = item;
        if (head == NULL)
        {
            ptr->next = NULL;
            head = ptr;
            printf("\nNode inserted");
        }
        else
        {
            temp = head;
            while (temp->next != NULL)
            {
                temp = temp->next;
            }
            temp->next = ptr;
            ptr->next = NULL;
            printf("\nNode inserted");

        }
    }
}

執行上面代碼,得到類似下麵的結果 -

Enter the item which you want to insert?
12

Node inserted
Press 0 to insert more ?
0

Enter the item which you want to insert?
23

Node inserted
Press 0 to insert more ?
2

上一篇: 鏈表 下一篇: 雙鏈表