5.1. 在單鏈表開頭插入節(jié)點

在鏈表的開頭將新元素插入節(jié)點非常簡單,只需要在節(jié)點鏈接中進行一些調(diào)整。要在開始時在鏈表中加入新節(jié)點,需要遵循以下步驟。

  • 為新節(jié)點分配空間并將數(shù)據(jù)存儲到節(jié)點的數(shù)據(jù)部分。這將通過以下聲明完成。
ptr = (struct node *) malloc(sizeof(struct node *));  
ptr -> data = data_item;
  • 使新節(jié)點的鏈接部分指向鏈表的現(xiàn)有第一個節(jié)點。這將通過使用以下語句來完成。
ptr->next = head;  
  • 最后,需要將新節(jié)點作為鏈表的第一個節(jié)點,這將通過使用以下語句來完成。
head = ptr;

算法

第1步:IF PTR = NULL
     則寫 OVERFLOW
     轉(zhuǎn)到步驟7
     [結(jié)束]

第2步:設(shè)置 NEW_NODE = PTR
第3步:SET PTR = PTR→NEXT
第4步:設(shè)置 NEW_NODE→DATA = VAL
第5步:設(shè)置NEW_NODE→NEXT = HEAD
第6步:SET HEAD = NEW_NODE
第7步:退出
image

C語言示例代碼:

#include<stdio.h>  
#include<stdlib.h>  

void beginsert(int);

struct node
{
    int data;
    struct node *next;
};
struct node *head;
void main()
{
    int choice, item;
    do
    {
        printf("Enter the item which you want to insert?\n");
        scanf("%d", &item);
        beginsert(item);
        printf("\nPress 0 to insert more ?\n");
        scanf("%d", &choice);
    } while (choice == 0);
}
void beginsert(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");
    }

}

執(zhí)行上面示例代碼,得到以下結(jié)果 -

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容