線性表的順序存儲

#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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章