本节介绍了C语言中的顺序表之判空、删除。
#include<stdio.h> #include<string.h> #include<stdlib.h> #define MAX 3 struct student { char name[20]; int id; int age; }; typedef struct student datatype_t; typedef struct { datatype_t num[MAX]; int n; }seqlist_t; seqlist_t * creat_seqlist() { seqlist_t *l=NULL; l=(seqlist_t *)malloc(sizeof(seqlist_t)); if(NULL==l) { printf("malloc is failed\n"); return NULL; } memset(l,0,sizeof(seqlist_t)); return l; } int full_list(seqlist_t *l) { return l->n==MAX?1:0; } int empty_list(seqlist_t*l) { return l->n==0?1:0; } int delete_list(seqlist_t*l,int id) { if(empty_list(l)) { return -2; } int i,j=0; for(i=0;i<l->n;i++) { if(l->num[i].id!=id) { l->num[j]=l->num[i]; j++; } } l->n=j; if(i==j) { return -1; }else{ printf("delete %d is successful!\n",id); } } void insert_seqlist(seqlist_t *l,datatype_t data) { strcpy(l->num[l->n].name,data.name); l->num[l->n].id=data.id; l->num[l->n].age=data.age; l->n++; } void printf_list(seqlist_t *l) { for(int i=0;i<l->n;i++) { printf("%s\t%d\t%d\n",l->num[i].name,l->num[i].id,l->num[i].age); } } int main() { seqlist_t *l=NULL; l=creat_seqlist(); datatype_t data; printf("please input tree data:"); while(!full_list(l)) { scanf("%s%d%d",data.name,&data.id,&data.age); insert_seqlist(l,data); } int ret; printf("next step: delete one data, please input one data:"); scanf("%d",&data.id); ret=delete_list(l,data.id); if(ret<0) { printf("no data or the num is empty!\n"); return -1; } else { printf_list(l); free(l); l=NULL; return 0; } }
运行结果
please input tree data:张三 1 23 李四 2 24 王五 3 25 next step: delete one data, please input one data:李四 2 24 delete 3 is successful! 张三 1 23 李四 2 24
C语言中的数据结构,实践练习了顺序表之判空、删除,感觉很有收获。