在單鏈表開頭插入節點

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

  • 為新節點分配空間並將數據存儲到節點的數據部分。這將通過以下聲明完成。

    ptr = (struct node *) malloc(sizeof(struct node *));
    ptr -> data = data_item;
    
  • 使新節點的鏈接部分指向鏈表的現有第一個節點。這將通過使用以下語句來完成。

    ptr->next = head;
    
  • 最後,需要將新節點作為鏈表的第一個節點,這將通過使用以下語句來完成。
    head = ptr;
    

演算法

第1步:IF PTR = NULL
     則寫 OVERFLOW
     轉到步驟7
     [結束]

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

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");
    }

}

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

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

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