本題要求實現遞增順序表的有序插入函數。L是一個遞增的有序順序表,函數Status ListInsert_SortedSq(SqList &L, ElemType e)用於向順序表中按遞增的順序插入一個數據。 比如:原數據有:2 5,要插入一個元素3,那么插入后順序表為2 3 5。 要考慮擴容的問題。
函數接口定義:
Status ListInsert_SortedSq(SqList &L, ElemType e);
裁判測試程序樣例:
//庫函數頭文件包含 #include<stdio.h> #include<malloc.h> #include<stdlib.h> //函數狀態碼定義 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; //順序表的存儲結構定義 #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 typedef int ElemType; //假設線性表中的元素均為整型 typedef struct{ ElemType* elem; //存儲空間基地址 int length; //表中元素的個數 int listsize; //表容量大小 }SqList; //順序表類型定義 //函數聲明 Status ListInsert_SortedSq(SqList &L, ElemType e); //順序表初始化函數 Status InitList_Sq(SqList &L) { //開辟一段空間 L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType)); //檢測開辟是否成功 if(!L.elem){ exit(OVERFLOW); } //賦值 L.length = 0; L.listsize = LIST_INIT_SIZE; return OK; } //順序表輸出函數 void ListPrint_Sq(SqList L) { ElemType *p = L.elem;//遍歷元素用的指針 for(int i = 0; i < L.length; ++i){ if(i == L.length - 1){ printf("%d", *(p+i)); } else{ printf("%d ", *(p+i)); } } } int main() { //聲明一個順序表 SqList L; //初始化順序表 InitList_Sq(L); int number = 0; ElemType e; scanf("%d", &number);//插入數據的個數 for(int i = 0; i < number; ++i) { scanf("%d", &e);//輸入數據 ListInsert_SortedSq(L, e); } ListPrint_Sq(L); return 0; } /* 請在這里填寫答案 */
輸入格式: 第一行輸入接下來要插入的數字的個數 第二行輸入數字 輸出格式: 輸出插入之后的數字
輸入樣例:
5 2 3 9 8 4
輸出樣例:
2 3 4 8 9
Status ListInsert_SortedSq(SqList &L, ElemType e) { if(L.length >= L.listsize){ L.elem = (ElemType*)realloc(L.elem, sizeof(ElemType)*(L.listsize+LISTINCREMENT)); L.listsize += LISTINCREMENT; if(!L.elem) exit(OVERFLOW); } ElemType *p = L.elem + L.length - 1; while(*p >= e && p >= L.elem){ *(p+1) = *p; --p; } *(p+1) = e; ++L.length; return OK; }
Status ListInsert_SortedSq(SqList &L, ElemType e) { if(L.length >= L.listsize){ L.elem = (ElemType*)realloc(L.elem,sizeof(L.listsize+LISTINCREMENT)); L.listsize += LISTINCREMENT; if(!L.elem) exit(OVERFLOW); } int i; for(i=L.length; i>0; i--){ if(L.elem[i-1] > e) L.elem[i] = L.elem[i-1]; else break; } L.elem[i] = e; L.length++; }