易百教程

使用函数来构建结构体的链表

创建函数以构建基于结构的链表。参考以下代码:

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

#define ITEMS 5 

struct Product {
    char symbol[5];
    int quantity;
    float price;
    struct Product *next;
};
struct Product *first;
struct Product *current;
struct Product *newCurrent;

struct Product *make_structure(void);
void fill_structure(struct Product *a, int c);
void show_structure(struct Product *a);

int main()
{
    int x;

    for (x = 0; x < ITEMS; x++)
    {
        if (x == 0)
        {
            first = make_structure();
            current = first;
        }
        else
        {
            newCurrent = make_structure();
            current->next = newCurrent;
            current = newCurrent;
        }
        fill_structure(current, x + 1);
    }
    current->next = NULL;

    /* Display database */
    puts("投资组合如下所示:");
    printf("代码\t数量\t价格\t总额\n");
    current = first;
    while (current)
    {
        show_structure(current);
        current = current->next;
    }
    system("pause");
    return(0);
}

struct Product *make_structure(void)
{
    struct Product *a;

    a = (struct Product *)malloc(sizeof(struct Product));
    if (a == NULL)
    {
        puts("Some kind of malloc() error");
        exit(1);
    }
    return(a);
}

void fill_structure(struct Product *a, int c)
{
    printf("项目 #%d/%d:\n", c, ITEMS);
    printf("股票代码: ");
    scanf("%s", a->symbol);
    printf("数量: ");
    scanf("%d", &a->quantity);
    printf("价格: ");
    scanf("%f", &a->price);
}
// 打印显示链表
void show_structure(struct Product *a)
{
    printf("%-6s\t%5d\t%.2f\t%.2f\n", \
        a->symbol,
        a->quantity,
        a->price,
        a->quantity*a->price);
}

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

项目 #1/5:
股票代码: H1
数量: 2
价格: 3.98
项目 #2/5:
股票代码: H2
数量: 345
价格: 19.0
项目 #3/5:
股票代码: H3
数量: 98
价格: 30
项目 #4/5:
股票代码: H4
数量: 489
价格: 6.9
项目 #5/5:
股票代码: H5
数量: 500
价格: 9.88
投资组合如下所示:
代码    数量    价格    总额
H1          2   3.98    7.96
H2        345   19.00   6555.00
H3         98   30.00   2940.00
H4        489   6.90    3374.10
H5        500   9.88    4940.00