本节介绍了C语言中的顺序表的创建、判满、输入、输出。
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 10 // 实际学⽣的存储 struct student { char name[20]; int id; int age; }; typedef struct student datatype_t; typedef struct { datatype_t buf[MAX]; // 定义数组记录班级学⽣每个学⽣的信息。 int n; // 学⽣实际到来的个数。 } seqlist_t; seqlist_t *create_empty_seqlist() { seqlist_t *t = NULL; t = (seqlist_t *)malloc(sizeof(seqlist_t)); if (NULL == t) { printf("malloc fail!"); return NULL; } memset(t, 0, sizeof(seqlist_t)); return t; } int is_full_seqlist(seqlist_t *l) { return l->n < MAX ? 0 : 1; } void insert_data_seqlist(seqlist_t *l, datatype_t data) { l->buf[l->n++] = data; } void printf_data_seqlist(seqlist_t *l) { printf("NAME\tID\tAGE\t\n"); for (int i = 0; i < l->n; i++) { datatype_t t = l->buf[i]; printf("%s%d%d\n", t.name, t.id, t.age); } } int main() { seqlist_t *st = NULL; st = create_empty_seqlist(); while (is_full_seqlist(st) != 1) { printf("please input student info\n"); datatype_t t; scanf("%s%d%d", &t.name, &t.id, &t.age); insert_data_seqlist(st, t); } printf_data_seqlist(st); return 0; }
运行结果
please input student info 20 20 20 please input student info 20 20 20 please input student info 20 20 20 please input student info 20 21 2 please input student info 21 22 23 please input student info 22 23 24 please input student info 25 26 23 please input student info 25 25 25 please input student info 45 58 69 please input student info 45 5 2 NAME ID AGE 202020 202020 202020 20212 212223 222324 252623 252525 455869 4552
C语言中的数据结构,实践练习了顺序表的创建、判满、输入、输出,感觉很有收获。