《資料結構題集》嚴蔚敏 2.11
阿新 • • 發佈:2019-01-12
有效程式碼: int InsertListOrder(List * L,int e);
int InsertListOrder(List * L,int e) { int * newbase; int i; if( (*L).length > (*L).size) { newbase = (int *)realloc((*L).elem, (LISTINCREMENT + (*L).size ) * sizeof(int)); if(!newbase) exit(ERROR); (*L).elem = newbase; (*L).size = LISTINCREMENT + (*L).size; } for(i = (*L).length;i>=1;i--) { if((*L).elem[i-1] > e) (*L).elem[i] = (*L).elem[i-1]; else break; } //雖然是用指標來代替靜態陣列,但還是可以用陣列這個形式滴 (*L).elem[i] = e; ++ (*L).length; return OK; }
全部程式碼:
#include<stdio.h> #include<stdlib.h> #define ERROR -1 #define OK 1 #define LIST_INT_SIZE 100 #define LISTINCREMENT 10 typedef struct { int * elem; int length; int size; }List; int InitList(List *L) { (*L).elem = (int *)malloc(LIST_INT_SIZE * sizeof(int)); if(!(*L).elem) exit(ERROR); (*L).length = 0; (*L).size = LIST_INT_SIZE; return OK; } int InsertList(List * L,int i,int e) { int * newbase,*q,*p; //int list1[5] = {3,5,7,9,11}; if(i<1 || i>(*L).length+1) return ERROR; if( (*L).length > (*L).size) { newbase = (int *)realloc((*L).elem, (LISTINCREMENT + (*L).size ) * sizeof(int)); if(!newbase) exit(ERROR); (*L).elem = newbase; (*L).size = LISTINCREMENT + (*L).size; } q = (*L).elem + i -1; //也就是插入點後面的元素都要往後挪一位 for( p = (*L).elem + (*L).length-1 ;p>=q;--p) { *(p+1) = *p; } *q = e; ++ (*L).length; return OK; } int InsertListOrder(List * L,int e) { int * newbase; //int list1[5] = {3,5,7,9,11}; //how to insert? int i; if( (*L).length > (*L).size) { newbase = (int *)realloc((*L).elem, (LISTINCREMENT + (*L).size ) * sizeof(int)); if(!newbase) exit(ERROR); (*L).elem = newbase; (*L).size = LISTINCREMENT + (*L).size; } for(i = (*L).length;i>=1;i--) { if((*L).elem[i-1] > e) (*L).elem[i] = (*L).elem[i-1]; else break; } //雖然是用指標來代替靜態陣列,但還是可以用陣列這個形式滴 (*L).elem[i] = e; ++ (*L).length; return OK; } int define_create(List *L,int n) { int i,j; int e; InitList(L); printf("please enter %d elements: ",n); scanf("%d",&e); InsertList(L,1,e);//if don't write like this divided,we can't get the result. for(i = 1;i<n;i++) //modify { scanf("%d",&e); for(j = 0;j<(*L).length;j++) if(e <= *((*L).elem + j) ) break; InsertList(L,j+1,e); //like this add order } return OK; } void ListTraverse(List L,void(*visit)(int *)) { int * q; q = L.elem; //for(;(q ++)!= NULL;) for(int i = 1;i<=L.length;i++) { visit(q++); } printf("\n"); } void visit(int * c) { printf(" %d ", *c ); } int main(int argc, char const *argv[]) { int n; List L; //why can't use List * InitList(&L); printf("please enter the List number: "); scanf("%d",&n); define_create(&L,n); InsertListOrder(&L,5); ListTraverse(L,visit); return 0; }
執行截圖: