在單鏈表指定節點之後插入節點

要在指定的節點之後將新節點插入到鏈表中,需要跳過鏈表中所需數量的節點,以將指針移動到插入節點之後的位置。通過使用以下語句來完成。

emp = head;
for (i = 0;i < loc;i++)
{
    temp = temp->next;
    if (temp == NULL)
    {
        return;
    }

}

為新節點分配空間,並將資料項目添加到節點的數據部分。這將通過使用以下語句來完成。

ptr = (struct node *) malloc (sizeof(struct node));
ptr->data = item;

現在,只需要進行一些鏈接調整,將節點插入到指定的位置。 因為,在迴圈結束時,迴圈指針temp將指向將插入新節點的節點。 因此,新節點ptr的下一部分必須包含temp的下一部分的地址(因為,ptr將在temptemp的下一個節點之間)。 這將通過使用以下語句來完成。

ptr -> next = temp -> next;

現在,只需要創建temp的下一部分,指向新節點ptr。 這將在指定位置插入新節點ptr

temp ->next = ptr;

演算法

步驟1:如果 PTR = NULL
輸出 OVERFLOW 提示
    轉到第12步

   結束時間

第2步:設置 NEW_NODE = PTR
第3步:NEW_NODE→DATA = VAL
第4步:設置 TEMP = HEAD
第5步:設置 I = 0
第6步:重複第5步和第6步直到 I
第7步:TEMP = TEMP→NEXT
第8步:如果 TEMP = NULL
輸出 “希望不存在的節點” 提示
     轉到第12步

    結束時間
  迴圈結束

第9步:PTR→NEXT = TEMP→NEXT
第10步:TEMP→NEXT = PTR
第11步:設置 PTR = NEW_NODE
第12步:退出

示意圖 -

C語言實現代碼 -

#include<stdio.h>
#include<stdlib.h>
void randominsert(int);
void create(int);
struct node
{
    int data;
    struct node *next;
};
struct node *head;
void main()
{
    int choice, item, loc;
    do
    {
        printf("\nEnter the item which you want to insert?\n");
        scanf("%d", &item);
        if (head == NULL)
        {
            create(item);
        }
        else
        {
            randominsert(item);
        }
        printf("\nPress 0 to insert more ?\n");
        scanf("%d", &choice);
    } while (choice == 0);
}
void create(int item)
{

    struct node *ptr = (struct node *)malloc(sizeof(struct node *));
    if (ptr == NULL)
    {
        printf("\nOVERFLOW\n");
    }
    else
    {
        ptr->data = item;
        ptr->next = head;
        head = ptr;
        printf("\nNode inserted\n");
    }
}
void randominsert(int item)
{
    struct node *ptr = (struct node *) malloc(sizeof(struct node));
    struct node *temp;
    int i, loc;
    if (ptr == NULL)
    {
        printf("\nOVERFLOW");
    }
    else
    {

        printf("Enter the location");
        scanf("%d", &loc);
        ptr->data = item;
        temp = head;
        for (i = 0;i < loc;i++)
        {
            temp = temp->next;
            if (temp == NULL)
            {
                printf("\ncan't insert\n");
                return;
            }

        }
        ptr->next = temp->next;
        temp->next = ptr;
        printf("\nNode inserted");
    }

}

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

Enter the item which you want to insert?
12

Node inserted

Press 0 to insert more ?
2

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