数据结构——线性表代码

线性表的插入和删除

#include <stdlib.h>
#include <stdio.h>

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
//线性表存储空间的初始分配量
#define LIST_INIT_SIZE 100
//线性表存储空间的分配增量
#define LISTINCREMENT 10
// Status 是函数的类型,其值是函数结果状态代码

typedef int Status;
typedef int ElemType;

typedef struct {
//存储空间基址
	ElemType *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.elem[0] = 1;
	L.elem[1] = 2;
	L.elem[2] = 3;
	L.elem[3] = 4;
	L.length = 4;
	L.listsize = LIST_INIT_SIZE;
	return OK;
}

//插入
Status ListInsert_Sq(SqList &L, int i, ElemType e) {
	ElemType *newbase,*q,*p;

	if(i < 1 || i > L.length + 1) {
		return ERROR;
	}
	if(L.length >= L.listsize) {
		newbase = (ElemType * )realloc(L.elem,
		                               (L.listsize + LISTINCREMENT) * sizeof(ElemType));
		if(!newbase) {
			exit(OVERFLOW);
		}
		L.elem = newbase;
		L.listsize += LISTINCREMENT;
	}
	q = &(L.elem[i - 1]);
	for(p = &(L.elem[L.length - 1]); p >= q; --p) {
		*(p + 1) = *p;
	}
	*q = e;
	++L.length;
	return OK;
}

//删除
Status ListDelete_Sq(SqList &L,int i,ElemType &e) {
	ElemType *q,*p;
	
	if((i < 1) || (i > L.length)) {
		return ERROR;
	}
	p = &(L.elem[i - 1]);
	e = *p;
	q = L.elem + L.length - 1;
	for(++p; p <= q; ++p) {
		*(p - 1) = *p;
	}
	--L.length;
	return OK;
}


//主函数
int main() {
	int i ;
	int a; 
	SqList L; 
	InitList_Sq(L);
	ListInsert_Sq(L, 1, 0);
	ListDelete_Sq(L , 1 ,a);
	for(i = 0;i < L.length;i++)
		printf("%d\t",L.elem[i]);
	printf("%d\t",a);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43525993/article/details/84242777