顺序表中基本操作的实现

#include<stdio.h>
typedef int A;
const int LIST_INIT_SIZE=100;
const int LISTINCREMENT=10;
typedef struct
{
	A *elem;
	int length;
	int listsize;
	int incrementsize;
}Sqlist;
//初始化操作
void InitList_Sq(Sqlist &L,int maxsize=LIST_INIT_SIZE,int incresize=LISTINCREMENT)
{
	L.elem=new A[maxsize];
	L.length=0;
	L.listsize=maxsize;
	L.incrementsize=incresize;
}
//顺序表追加空间的函数
void increment(Sqlist &L)
{
	A *a,i;
	a=new A[L.listsize+L.incrementsize];
	for(i=0;i<L.length;i++)
		a[i]=L.elem[i];
	delete[]L.elem;
	L.elem=a;
	L.listsize+=L.incrementsize;
}
//插入元素操作
bool ListInsert_Sq(Sqlist &L,int i,A e)
{
	if(i<1||i>L.length+1)
	{
		printf("i值不合法
");
		return false;
	}
	else
	{
	A *p,*q;
	if(L.length>=L.listsize)
		increment(L);
	q=&(L.elem[i-1]);
	for(p=&(L.elem[L.length-1]);p>=q;--p)
		*(p+1)=*p;
	*q=e;
	++L.length;
	return true;
	}

}
int main()
{
	Sqlist L;
	A n;
	scanf("%d",&n);
	InitList_Sq(L);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&L.elem[i]);
		L.length++;
	}
	for(i=0;i<n;i++)
		printf("%d ",L.elem[i]);
	printf("
");
    A e;
	scanf("%d%d",&i,&e);
	bool f = ListInsert_Sq(L,i,e);  //将e插在第i个数的前面
	{
		if(f==true)
		{
			for(i=0;i<n+1;i++)
				printf("%d ",L.elem[i]);
			printf("
");
		}
	}
	return 0;
}

原文地址:https://www.cnblogs.com/NYNU-ACM/p/4237363.html