第2章 线性表——顺序线性表插入和表示学生信息

来源:互联网 发布:当幸福来敲门影评知乎 编辑:程序博客网 时间:2024/05/22 06:51
/* *    这个程序首先构建一个空的顺序线性表, *    之后插入学生信息完成线性表的建立。 */#include<stdio.h>#include<stdlib.h>#define LIST_INIT_SIZE 100  #define LISTINCREMENT 10  typedef struct Elemtype{ /*学生的相关信息*/long num;double score;}Elemtype;typedef struct student { /*线性表地址、长度*/Elemtype *elem;          int length;int listsize;        }student;int initlist(student *L){    /*构造一个空线性表*/L->elem= (Elemtype *)malloc(LIST_INIT_SIZE*sizeof(Elemtype));if(!L->elem)return 0;L->length = 0;L->listsize = LIST_INIT_SIZE;return 1;}int listinsert(student *L,int i,long num,double score){ /*插入新元素 e */Elemtype *newbase,*q,*p;if(i<1||i>L->length+1)return 0;if(L->length>=L->listsize){newbase = (Elemtype *)realloc((L->elem) ,(L->listsize+LISTINCREMENT)*sizeof(Elemtype));     if(!newbase)    return 0;L->elem = newbase;   L->listsize = L->listsize+LISTINCREMENT; }q = &(L->elem[i-1]);    for((p = &L->elem[L->length-1]);p>=q;p--)*(p+1) = *p;    scanf("%ld%lf",&q->num,&q->score);L->length++;     return 1;}int main(){student A;int i,a;long num;double score;A.length=0;A.listsize=LIST_INIT_SIZE;if(initlist(&A)){printf("空线性表构造成功!\n");for(i = 0;i<=4;i++)a = listinsert(&A,i+1,num,score);for(i = 0;i<=4;i++){printf("%d\n",a);printf("%ld    %.1lf\n",A.elem[i].num,A.elem[i].score);}}elseprintf("空线性表构造失败!\n");return 0;}/*      测试案例: *      输入: * *           0001 10 *           0002 20 *           0003 30 *           0004 40 *           0005 50 * *      输出: *           空线性表构造成功! *           1 *           1    10.0 *           1 *           2    20.0 *           1 *           3    30.0 *           1 *           4    40.0 *           1 *           5    50.0 */

原创粉丝点击