#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
//结构体构建
typedef struct SqList{
int *elem;
int length;
int listsize;
}SqList;
//建立空线性表
Status InitList_Sq(SqList &L){
L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType)); //分配空间
if(!L.elem)exit(OVERFLOW);//空间分配失败
L.length=0;
L.listsize= LIST_INIT_SIZE;//设置顺序表长度、空间
return OK;
}
//对顺序表赋值
Status NumList_Sq(SqList &L){
L.length=5;//假设原始表长为 5
printf("请输入顺序表内的五个数字:");
for(int i=0;i<L.length;i++)
scanf("%d",&L.elem[i]);
}
// 按序插入x
Status InsertX_B(SqList &L, int x){
if(L.length>=L.listsize) //判断表满
{
ElemType *newbase;
newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType)); //增加空间
if(!newbase)exit(OVERFLOW);
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
for(int i=0;i<L.length;i++)//遍历线性表,找到x的位置
{
if(L.elem[i]>=x)
{
for(int j=L.length;j>=i;j--)//移动元素,插入x
{
L.elem[j]= L.elem[j-1];
}
L.length+=1;
L.elem[i]=x;
break;
}
}
}
//主函数
int main()
{
printf("请输入要插入的值x:");
int x;
scanf("%d",&x);
SqList L;
InitList_Sq(L);
NumList_Sq(L);
InsertX_B(L, x);
printf("插入后的顺序表为:");
for(int i=0;i<L.length;i++)
printf("%d ",L.elem[i]);
return 0;
}
顺序表练习:设顺序表L是一个递增有序表,试写一算法,将x插入其后仍保持L的有序性。
最新推荐文章于 2022-10-22 09:00:42 发布