已知顺序表中的元素依值递增有序排列,要求将x插入到顺序表的适当位置上,使得插入操作后的顺序表仍保持有序性。
# include <stdio.h>
# include <stdlib.h>
# define initsize 20
# define LISTINCREMENT 5
typedef int ElemType;
typedef struct
{
ElemType * elem;
int length;
int listsize;
}SqList;
void IntiList(SqList &L,int n)
{
ElemType *p;
L.elem = (ElemType *)malloc(initsize*sizeof(ElemType));
if(!L.elem)
{
printf("分配失败");
}
printf("请依次输入顺序表的元素(元素依值递增顺序输入):\n");
for(p = L.elem;p < L.elem+n;p++)
{
scanf("%d",p);
}
L.length = n;
L.listsize = initsize;
}
void ListInsert(SqList &L,int i,ElemType e)
{
void PrintList(SqList L);
ElemType *p,*q,*newbase;
q=L.elem+i-1;
if(i<1||i>L.length+1)
{
printf("插入元素位置不合法\n");
}
if(L.length>=L.listsize)
{
newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
if(!newbase)
{
printf("分配失败");
}
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
for(p=L.elem+L.length-1;p>=q;p--)
{
*(p+1)=*p;
}
*q=e;
++L.length;
PrintList(L);
}
void PrintList(SqList L)
{
ElemType *p;
printf("输出顺序表中的元素\n");
for(p=L.elem;p<L.elem+L.length;p++)
{
printf("%d\t",*p);
}
printf("\n");
}
int main()
{
int n,i;
ElemType x,*p;
SqList L;
printf("请输入要建立的顺序表的长度n:\n");
scanf("%d",&n);
IntiList(L,n);
printf("请输入要插入的元素x=\n");
scanf("%d",&x);
for(i=1,p=L.elem;p<L.elem+L.length && *p<x;p++)
{
++i;
}
ListInsert(L,i,x);
return 0;
}