首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C 語言鏈表操作(一):動態創建鏈表完整指南

     編輯:關於C

為什麼需要鏈表?

數組需預先固定長度,難以應對元素數量不確定的場景,且可能造成內存浪費。鏈表採用動態內存分配,節點在內存中可不連續,按需申請釋放,靈活高效。

鏈表核心結構

struct student {
    long num;           // 學號
    float score;        // 成績
    struct student *next; // 指向下一節點的指針
};

關鍵點:

  • next 指針將離散節點串聯成鏈
  • 必須保存頭指針 head,否則無法訪問鏈表
  • 尾節點的 next 置為 NULL 標記結束

創建鏈表完整代碼

#include <stdlib.h>
#include <stdio.h>
#define NULL 0
#define LEN sizeof(struct student)

struct student {
    long num;
    float score;
    struct student *next;
};

int n; // 全局節點計數器

struct student *creat(void) {
    struct student *head, *p1, *p2;
    n = 0;
    p1 = p2 = (struct student *)malloc(LEN);
    scanf("%ld,%f", &p1->num, &p1->score);
    head = NULL;
    
    while (p1->num != 0) { // 以學號為0作為輸入結束標記
        n++;
        if (n == 1)
            head = p1;
        else
            p2->next = p1;
        p2 = p1;
        p1 = (struct student *)malloc(LEN);
        scanf("%ld,%f", &p1->num, &p1->score);
    }
    p2->next = NULL;
    return head;
}

void main() {
    creat();
}

關鍵邏輯詳解

  1. 雙指針法:p1 指向新節點,p2 指向前一節點,便於連接
  2. 首節點處理:第一個節點直接賦值給 head
  3. 後續節點連接:p2->next = p1 將新節點掛在尾部
  4. 指針後移:p2 = p1 更新尾指針
  5. 終止條件:輸入學號為 0 時結束,最後將尾節點 next 置 NULL

內存佈局示意

鏈表內存結構圖

每個節點包含數據域(num、score)和指針域(next),通過 next 串聯形成邏輯順序。

常見錯誤避坑

  • 忘記檢查 malloc 返回值(生產代碼必須加錯誤處理)
  • 未將尾節點 next 置 NULL,導致遍歷越界
  • 輸入格式不匹配 scanf 格式字符串
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved