顺序表的插入
描述
先读入数据建立顺序表va,表中的数据元素递增有序,再读入一个整数x,将它插入到顺序表中的适当位置,并保持顺序表的有序性。
输入
先输入一个小于100的正整数n,紧接着读入n个从小到大的正整数,建立顺序表,最后再读入一个正整数x,把它插入到顺序表中的适当位置,并保持顺序表的有序性。
输出
按顺序输出整个顺序表,输出的每个元素占一行。
输入样例
4
2 100 3000 3890
200
输出样例
2
100
200
3000
3890
提示
输出语句为:printf(“%d\n”);
#include <stdio.h>
#include <stdlib.h>
typedef int DataType; /*数据类型*/
typedef int ElemType; /*元素类型*/
//--------------线性表的动态顺序存储结构------------
#define LIST_INIT_SIZE 100 //线性表存储空间的初始分配量
#define LISTINCREMENT 10 //线性表存储空间的分配增量
typedef struct
{
ElemType *elem; //存储空间基址
int length; //当前长度
int listsize; //当前分配的存储容量
}SqList;
void InitList(SqList *L)
//初始化
{
L->elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));//分配空间
L->length = 0; //空表的长度为0
L->listsize = LIST_INIT_SIZE; //初始容量
}
void CreateList(SqList *L, int n)
{
InitList(L); //初始化
int i;
for(i = 0; i < n; i ++)
{
scanf("%d", &L->elem[i]);
L->length++;
}
}
void InsertList(SqList *L, int e)
{
int i;
//从顺序表最后一位开始,将所有大于e的元素向后移动
for(i = L->length-1; L->elem[i] > e; i--)
{
L->elem[i+1] = L->elem[i];
}
//插入之
L->elem[i] = e;
L->length++;
}
void ListTraverse(SqList *L)
{
int n = L->length, i;
for(i = 0; i < n; i++)
printf("%d\n", L->elem[i]);
}
int main()
{
SqList L;
int n;
scanf("%d", &n);
CreateList(&L, n);
int e;
scanf("%d", &e);
InsertList(&L, e);
ListTraverse(&L);
return 0;
}