线性表的顺序存储

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

#define OK 0
#define ERROR -1
#define ElemType int

#define INIT_LENGTH 10		//数组初始容量
#define INCREMENT 20		//重新分配内存时的增量

typedef struct 
{
	ElemType *pBase;	//数组的基址
	int length;			//数组的当前长度
	int size;			//数组的容量
}SqList;

//初始化线性表
int initList(SqList *list);
//在线性表list的pos位置插入元素e,pos从1开始
int insertList(SqList *list, int pos, ElemType e);
//删除线性表中位置为pos的元素,并返回该元素
int removeList(SqList *list, int pos, ElemType *e);
//遍历整个线性表
void traverse(SqList list);

int main()
{
	SqList list;
	initList(&list);
	for (int i=1; i<=500; i++)
		insertList(&list, i, i);
	int e;
	printf("len:%d\n", list.length);
	removeList(&list, 1, &e);
	printf("len:%d\n", list.length);
	printf("remove:%d\n", e);
	traverse(list);
	system("pause");
	return 0;
}

int initList(SqList *list)
{
	list->pBase = (ElemType *)malloc(INIT_LENGTH * sizeof(ElemType));
	if (!list->pBase)
	{
		printf("内存分配失败,程序将退出\n");
		exit(-1);
	}
	list->size = INIT_LENGTH;
	list->length = 0;
	return OK;
}

int insertList(SqList *list, int pos, ElemType e)
{
	if (pos < 1 || pos > list->length + 1)
	{
		printf("插入位置非法\n");
		return ERROR;
	}
	//数组已满,需要重新分配内存
	if (list->length >= list->size)
	{
		//realloc当重新分配空间时,若原来基址所在的连续空间不够,则会新分配另外一段连续的存储空间,并自动把原来空间中的元素复制到新的存储空间,
		//然后把新存储空间的首地址返回
		ElemType *newBase = (ElemType *)realloc(list->pBase, (list->size + INCREMENT) * sizeof(ElemType));
		if (!newBase)
		{
			printf("重新分配内存失败,程序将退出\n");
			exit(-1);
		}
		list->pBase = newBase;
		list->size += INCREMENT;
	}
	for (int i=list->length-1; i>=pos-1; i--)
	{
		list->pBase[i+1] = list->pBase[i];
	}
	list->pBase[pos - 1] = e;
	list->length++;

	return OK;
}

int removeList(SqList *list, int pos, ElemType *e)
{
	if (pos < 1 || pos > list->length)
	{
		printf("删除元素位置非法\n");
		return ERROR;
	}
	//取出待删除的元素
	*e = list->pBase[pos - 1];
	//从待删元素位置后依次向前移动该元素
	for (int i=pos; i<list->length; i++)
	{
		list->pBase[i-1] = list->pBase[i];
	}
	//表长-1
	list->length--;
	return OK;
}

void traverse(SqList list)
{
	for (int i=0; i<list.length; i++)
		printf("%d ", list.pBase[i]);
	printf("\n");
}

发布了33 篇原创文章 · 获赞 10 · 访问量 5万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章