本題要求將任一給定元素插入從大到小排好序的數組中合適的位置,以保持結果依然有序。
函數接口定義:
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;
}
/* 你的代碼將被嵌在這裏 */
Solution
bool Insert( List L, ElementType X ){
if(L->Last == MAXSIZE - 1) return false;
int i = 0;
for(; L->Data[i] >= X && i <= L->Last; i++)
if(L->Data[i] == X)
return false;
for(int j = L->Last + 1; j > i; j--)
L->Data[j] = L->Data[j - 1];
L->Data[i] = X;
L->Last++;
return true;
}