#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node_s{ char *data; struct node_s *next; }node_t; node_t *create(){ node_t *p = calloc(1, sizeof(node_t)); return p; } int insert(node_t *head, const char *data){ node_t *new = create(); if(!new){ return -1; } new->data = strdup(data); new->next = head->next; head->next = new; return 0; } int clear(node_t *head){ node_t *p_next; if(!head){ return -1; } while(head->next != NULL){ p_next = head->next; if(head->data){ free(head->data); } free(head); head=p_next; } return 0; } #define foreach(head, a_unit) for(head = head->next, a_unit = head; head != NULL; head = head->next, a_unit = head) int main(){ node_t *head = create(); insert(head, "a"); insert(head, "b"); insert(head, "c"); node_t *a_unit; foreach(head, a_unit){ printf("%s\n", a_unit->data); } clear(head); }
时间: 2024-10-27 12:07:27