習題1.9 有序數組的插入 (20分)
本題要求將任一給定元素插入從大到小排好序的數組中合適的位置,以保持結果依然有序。
函數接口定義:
bool Insert( List L, ElementType X );
其中List
結構定義如下:
typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存線性表中最后一個元素的位置 */ };
L
是用戶傳入的一個線性表,其中ElementType
元素可以通過>、=、<進行比較,並且題目保證傳入的數據是遞減有序的。函數Insert
要將X
插入Data[]
中合適的位置,以保持結果依然有序(注意:元素從下標0開始存儲)。但如果X
已經在Data[]
中了,就不要插入,返回失敗的標記false
;如果插入成功,則返回true
。另外,因為Data[]
中最多只能存MAXSIZE
個元素,所以如果插入新元素之前已經滿了,也不要插入,而是返回失敗的標記false
。
裁判測試程序樣例:
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 typedef enum {false, true} bool; typedef int ElementType; typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存線性表中最后一個元素的位置 */ }; List ReadInput(); /* 裁判實現,細節不表。元素從下標0開始存儲 */ void PrintList( List L ); /* 裁判實現,細節不表 */ bool Insert( List L, ElementType X ); int main() { List L; ElementType X; L = ReadInput(); scanf("%d", &X); if ( Insert( L, X ) == false ) printf("Insertion failed.\n"); PrintList( L ); return 0; } /* 你的代碼將被嵌在這里 */
輸入樣例1:
5
35 12 8 7 3
10
輸出樣例1:
35 12 10 8 7 3
Last = 5
輸入樣例2:
6
35 12 10 8 7 3
8
輸出樣例2:
Insertion failed.
35 12 10 8 7 3
Last = 5
單位: 浙江大學
時間限制: 1000 ms
內存限制: 64 MB
AC代碼如下:
bool Insert(List L, ElementType X) { int i=0, tag; while(L->Data[i]>X)//數組data[]是遞減排序的,此處是找x應該插入的位置,下標從0開始。第一個比x小的元素的下標就是這個位置 { i++; } tag = i; if(L->Data[tag]==X||(L->Last+1)>=MAXSIZE)//如果x已經在data[]中或者data[]中元素數量超過10 return false; for(i= L->Last;i>=tag;i--)//元素后移 { L->Data[i+1] = L->Data[i]; } L->Data[tag] = X;//將X放入第tag位 L->Last++; return true; }