链表(C语言实现)

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值