首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言結構體指標鏈表建立完整教學:從節點定義到插入刪除

     編輯:程式設計綜合問答

題目結構定義


struct ipaddr_t { int size; char* ipaddr; };
struct msg_t    { int size; char* msg;    };
struct node_t {
    int port;
    struct ipaddr_t* ipaddr_h;
    struct msg_t* msg;
    struct node_t* next;
};

完整實作範例


#include 
#include 
#include 

// 建立節點
struct node_t* create_node(int port, const char* ip, const char* msg) {
    struct node_t* n = malloc(sizeof(struct node_t));
    n->port = port;
    n->ipaddr_h = malloc(sizeof(struct ipaddr_t));
    n->ipaddr_h->size = strlen(ip);
    n->ipaddr_h->ipaddr = strdup(ip);
    n->msg = malloc(sizeof(struct msg_t));
    n->msg->size = strlen(msg);
    n->msg->msg = strdup(msg);
    n->next = NULL;
    return n;
}

// 尾插
void append(struct node_t** head, struct node_t* n) {
    if (!*head) { *head = n; return; }
    struct node_t* p = *head;
    while (p->next) p = p->next;
    p->next = n;
}

// 列印
void print_list(struct node_t* head) {
    for (struct node_t* p = head; p; p = p->next) {
        printf("Port:%d IP:%s Msg:%s\n", p->port, p->ipaddr_h->ipaddr, p->msg->msg);
    }
}

// 釋放
void free_list(struct node_t* head) {
    while (head) {
        struct node_t* nxt = head->next;
        free(head->ipaddr_h->ipaddr);
        free(head->ipaddr_h);
        free(head->msg->msg);
        free(head->msg);
        free(head);
        head = nxt;
    }
}

int main() {
    struct node_t* head = NULL;
    append(&head, create_node(8080, "192.168.1.1", "hello"));
    append(&head, create_node(9090, "10.0.0.1", "world"));
    print_list(head);
    free_list(head);
    return 0;
}

關鍵點總結

  • 每個指標成員(ipaddr_h, msg, next)皆需單獨 malloc。
  • 字串欄位用 strdup 複製,記得配對 free。
  • 雙重指標 **head 使函式能修改呼叫端的頭指標。
  • 生產環境建議封裝為「帶頭尾指標的雙向鏈表」或使用成熟庫(glib, klib)。

參考資源

C 語言鏈表圖文教學:從零開始學鏈表

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