#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct food {
char name[256];
float price;
};
typedef struct food Item;
struct node {
Item *item;
struct node *next;
};
typedef struct node Node;
struct linklist {
Node *head;
Node *tail;
unsigned int size;
};
typedef struct linklist LinkList;
void list_init(LinkList *list)
{
list->size = 0;
list->head = NULL;
list->tail = NULL;
}
void list_add(LinkList *list, Item *item)
{
Node *node = (Node *)malloc(sizeof(Node));
Item *new_item = (Item *)malloc(sizeof(Item));
strcpy(new_item->name, item->name);
new_item->price = item->price;
if (!node) return;
node->item = new_item;
node->next = NULL;
if (list->head == NULL) {
list->head = node;
list->tail = node;
list->size++;
} else {
list->tail->next = node;
list->tail = node;
list->size++;
}
}
Item* list_get_by_name(const LinkList *list, char *name)
{
Node *node = list->head;
while (node != NULL) {
if (strcmp(name, node->item->name) == 0)
return node->item;
node = node->next;
}
return NULL;
}
void list_clear(LinkList *list)
{
Node *node = list->head;
while (node != NULL) {
Node *temp = node->next;
free(node);
node = temp;
}
list->size = 0;
list->head = NULL;
list->tail = NULL;
free(list);
}
int main()
{
LinkList *list = (LinkList *)malloc(sizeof(LinkList));
list_init(list);
Item item1;
strcpy(item1.name, "Apple");
item1.price = 12.6;
Item item2;
strcpy(item2.name, "Pear");
item2.price = 30.94;
Item item3;
strcpy(item3.name, "Meat");
item3.price = 28.39;
list_add(list, &item1);
list_add(list, &item2);
list_add(list, &item3);
printf("name: %s\n", item1.name);
printf("price: %.1lf\n", item1.price);
Item *pitem = list_get_by_name(list, "Pear");
if (pitem) {
printf("name: %s\n", pitem->name);
printf("price: %.2lf\n", pitem->price);
}
list_clear(list);
return 0;
}
参考:http://www.srcmini.com/1273.html