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

C語言單向鏈表實作圖解:從結構定義到完整程式碼

     編輯:關於C語言
 

單向鏈表節點結構

每個節點包含資料欄位與指向下一節點的指標:

struct node {
    int data;              // 資料欄位,可為多種型別
    struct node *next;     // 指標欄位,僅能有一個
};

單向鏈表示意圖

核心概念

  1. 鏈表結合結構體與指標,由頭、中間、尾節點組成單向可伸縮鏈結。
  2. 每個節點用結構體表示,含資料成員與結構指標成員。
  3. 資料成員存放用戶資料;指標成員連接下一節點,因指向相同結構體類型,稱為結構指標變數。
  4. 鏈表長度動態:需要新節點時向系統申請記憶體 (malloc),直到指標指向 NULL 為止。
    申請空間語法:(struct node*)malloc(sizeof(struct node))

鏈表建立步驟

設有指標變數 struct node *p, *p1, *head;

  • head:標記鏈表頭。
  • p:建立過程中暫存新節點位址。
  • p1->next:儲存新節點位址,串聯鏈表。

第一步:建立第一個節點

head = p1 = p = (struct node *)malloc(sizeof(struct node));

建立頭節點

第二步:賦值資料並產生第二個節點

scanf("%d", &p->data);  // 輸入 10
p = (struct node *)malloc(sizeof(struct node));

產生第二節點

第三步:串聯第一、二節點

p1->next = p;

串聯節點

第四步:產生第三節點並重複

p1 = p;
scanf("%d", &p->data);  // 輸入 8
p = (struct node *)malloc(sizeof(struct node));

重複步驟 3、4,直到輸入結束條件(如 0),最後設定尾節點 p->next = NULL。

完整程式碼

#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct node)

struct node {
    int data;
    struct node *next;
};

int main() {
    struct node *p, *p1, *head;
    head = p = (struct node *)malloc(LEN);
    scanf("%d", &p->data);           // 頭節點資料
    while (p->data != 0) {           // 0 為結束條件
        p1 = p;
        p = (struct node *)malloc(LEN);
        scanf("%d", &p->data);       // 中間節點資料
        p1->next = p;                // 串聯
    }
    p->next = NULL;                  // 尾節點
    // 顯示鏈表
    p = head;
    printf("鏈表資料成員為:");
    while (p->next != NULL) {
        printf("%d", p->data);
        p = p->next;
    }
    printf("%d\n", p->data);
    return 0;
}

程式執行結果

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved