第2章 線性表——順序線性表插入和表示學生資訊

來源:互聯網
上載者:User
/* *    這個程式首先構建一個空的順序線性表, *    之後插入學生資訊完成線性表的建立。 */#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 */

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.