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 使函式能修改呼叫端的頭指標。C 語言鏈表圖文教學:從零開始學鏈表