C语言线性表的问题 目前不学写。
// StudentEx_2_Ex4.cpp : Defines the entry point for the console application.
问题:设线性表存于数组a[0… n-1]的前R个分量中,且递增有序,试写一算法,将x插入到线性表的适当位置上,以保持线性表的有序性。
假设 n=20,R=10;
//
#include “stdio.h”
#include “stdlib.h”
#include “windows.h”
#define INIT_SIZE 100
#define INCREMENT 20
typedef int ElemType;typedef struct {
ElemType* elem;//存储空间基地址
int length; //当前长度
int listsize; //容量
}SqList;void listPrint(SqList L) {
for (int i = 0; i < L.length; i++) {
printf("%5d", L.elem[i]);
}
printf("\n");
}
//在顺序表L的第i个位置前插入新元素e,成功返回1,失败返回0
int SqListInsert(SqList* L, int i, ElemType e) {
//判断插入位置是否合法
if (i<1 || i>L->length + 1)
return 0;
//判断表是否满,如果表满,增加空间
if (L->length >= L->listsize) {
ElemType* newBase = (ElemType*)realloc(L->elem, (L->listsize + INCREMENT) * sizeof(ElemType));
if (newBase == NULL)
return 0;
L->elem = newBase;
L->listsize = L->listsize + INCREMENT;
}
//移空
for (int j = L->length - 1; j >= i - 1; j–) {
L->elem[j + 1] = L->elem[j];
}
//填空
L->elem[i - 1] = e;
//改长度
L->length = L->length + 1;
return 1;
}
int listLocate(SqList L, ElemType e) {
int loc = 1;
//请同学们填入核心代码
}
int main()
{
ElemType a[20];
for (int i = 0; i < 10; i++) {
a[i] = 2 * i + 1;
}
SqList sq;
sq.elem = a;
sq.length = 10;
sq.listsize = 20;
listPrint(sq);
int loc = listLocate(sq, 4);
SqListInsert(&sq, loc, 4);
listPrint(sq);
Sleep(50000);
return 0;
}
**