这道题真的花了我超久的时间,解题中比较重要的有在线性表当中插入新数时,从线性表最后一个开始吧要插入节点之后(包括该节点)的数据全部向后挪一格,这样的处理方法是最简便的。还有就是Last和length这两个,一个是数组中最后一个数据的位置一个是数据的数量,始终差1,在编写函数时需要注意。
本题要求将任一给定元素插入从大到小排好序的数组中合适的位置,以保持结果依然有序。
1.9有序数组的插入:
函数接口定义:
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
下面给出我的答案:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 10
typedef int ElementType;
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};
List ReadInput(void); /* 裁判实现,细节不表。元素从下标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");
printf("X=%d\n",X);
PrintList( L );
return 0;
}
void PrintList( List L ){
for (int i=0;i<=L->Last;i++) {
printf("%d ",L->Data[i]);
}
printf("\nLast = %d",L->Last);
}
List ReadInput(){
List La=(List)malloc(sizeof(List));
int length=0;
scanf("%d",&length);
for (int i=0;i<length;i++){
scanf("%d",&La->Data[i]);
}
La->Last=length-1;
return La;
}
/* 你的代码将被嵌在这里 */
bool Insert( List L, ElementType X ){
int length=L->Last+1;
int i=1;
if(length>=MAXSIZE)
return false;
for(i=0;i<=L->Last;i++){
if(X==L->Data[i])
return false;
if(X>L->Data[i]){
for (int j =L->Last+1;j>i;j--) {
L->Data[j]=L->Data[j-1];
}
L->Data[i]=X;
L->Last=length;
return true;
}
}
i--;
if(L->Data[i]>X){
L->Data[i+1]=X;
L->Last++;
return true;
}
return false;
}