易百教程

使用结构体创建链表

如何使用结构体创建链表?请参考以下代码:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main()
{
    struct Product {
        char symbol[5];
        int quantity;
        float price;
        struct Product *next;
    };
    struct Product *first;
    struct Product *current;
    struct Product *newNode;

    /* 在内存中创建结构 */
    first = (struct Product *)malloc(sizeof(struct Product));
    if (first == NULL)
    {
        puts("Some kind of malloc() error");
        exit(1);
    }

    /* 分配结构数据 */
    current = first;
    strcpy(current->symbol, "ABCD");
    current->quantity = 100;
    current->price = 801.19;
    current->next = NULL;

    newNode = (struct Product *)malloc(sizeof(struct Product));
    if (newNode == NULL)
    {
        puts("Another malloc() error");
        exit(1);
    }
    current->next = newNode;
    current = newNode;
    strcpy(current->symbol, "MSFT");
    current->quantity = 100;
    current->price = 28.77;
    current->next = NULL;

    /* 显示数据库 */
    puts("投资组合信息:");
    printf("代码\t数量\t价格\t总值\n");
    current = first;
    printf("%-6s\t%5d\t%.2f\t%.2f\n", \
        current->symbol,
        current->quantity,
        current->price,
        current->quantity*current->price);
    current = current->next;
    printf("%-6s\t%5d\t%.2f\t%.2f\n", \
        current->symbol,
        current->quantity,
        current->price,
        current->quantity*current->price);

    system("pause");
    return(0);
}

执行上面示例代码,得到以下结果:

投资组合信息:
代码    数量    价格    总值
ABCD      100   801.19  80119.00
MSFT      100   28.77   2877.00

代码创建了第二个结构体,链接到第一个结构体。该代码声明了链表所需的标准三个结构体指针。NULL值限制链表的结尾。