数据结构——顺序表-插入算法

#include
#include 
#define SIZE  100
#define  INCREMENT_SIZE 10

typedef struct{
	int *elem; 
	int length;
	int listsize;
}Sqlist;

bool InintList_Sq(Sqlist &L){
	L.elem = (int*)malloc(SIZE*sizeof(int));
	if(!L.elem)
		return false;
	L.length = 0;
	L.listsize = SIZE;
	return true;
}

bool Insert(Sqlist &L,int pos,int data){
	int *newbase;
	if(pos < 1||pos > L.length+1)
		return false;
	if(L.length >= L.listsize){
		newbase = (int*)realloc(L.elem,(L.listsize+INCREMENT_SIZE)*sizeof(int));
		if(!newbase)
			return false;
		L.elem = newbase;
		L.listsize += INCREMENT_SIZE;
	}
//	for(int i=L.length-1;i>=pos-1;i--)
//		L.elem[i+1] = L.elem[i];
//	L.elem[pos-1] = data;
//	L.length += 1;
	int *q = &L.elem[pos-1];
	for(int *p=&L.elem[L.length-1];p>=q;p--)
		*(p+1) = *p;
	*q = data;
	L.length++;
	return true;
}
int main(){
	int pos;int data;
	Sqlist sql;
	InintList_Sq(sql);
	printf("请输入输入数据的个数:"); 
	scanf("%d",&sql.length);
	for(int i=0;i

 

你可能感兴趣的:(考研数据结构代码,c++,考研,数据结构)