2021-10-14:数据结构顺序表

2021年10月14日
复习内容:数据结构顺序表
代码练习:顺序表的初始化、增删、查找、打印、释放顺序表;
代码用时:40分钟
代码示例:

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

#define SIZE 10;
typedef int ElemType;
typedef struct
{
    
    
	ElemType* data;
	int cur_size;
	int all_size;

}Seqlist;

//初始化
void Init_Seqlist(Seqlist* sq);
//插入数据
int Insert(Seqlist* sq, ElemType value, int pos);
//扩容
int ApplyNewSpace(Seqlist* sq, int newsize);
//删除数据
int DeleteOfValue(Seqlist* sq, ElemType value);
//查找数据
int SearchOfValue(Seqlist* sq, ElemType value);
//删除顺序表
void FreeSeqList(Seqlist* sq);
//打印
void ShowSeqlist(Seqlist* sq);

//初始化
void Init_Seqlist(Seqlist* sq)
{
    
    
	if (sq == NULL) return;
	sq->all_size = SIZE;
	sq->cur_size = 0;
	sq->data = (ElemType*)malloc(sizeof(ElemType) * sq->all_size);
	memset(sq->data, 0, sq->all_size);
}

//扩容
int ApplyNewSpace(Seqlist* sq, int newsize)
{
    
    
	if (sq == NULL) return -1;
	if (newsize <= 0) return -1;

	Seqlist new_sq;
	new_sq.data = (ElemType*)malloc(sizeof(ElemType) * newsize);
	if (new_sq.data == NULL) return -1;

	//转移数据
	for (int i = 0; i < sq->cur_size; i++)
	{
    
    
		new_sq.data[i] = sq->data[i];
	}

	free(sq->data);
	sq->data = new_sq.data;
	sq->all_size = newsize;
	return 0;

}

//插入数据
int Insert(Seqlist* sq, ElemType value, int pos)
{
    
    
	if (sq == NULL) return -1;
	if (pos > sq->cur_size || pos < 0) return -1;
	if (sq->cur_size == sq->all_size)
	{
    
    
		//扩容
		if (ApplyNewSpace(sq, (int)(1.5 * sq->all_size)) == -1)
			return -1;
	}

	for (int i = sq->cur_size; i > pos ; i--)
	{
    
    
		sq->data[i] = sq->data[i - 1];
	}
	sq->data[pos] = value;
	sq->cur_size++;
	return 0;

}

//删除数据
int DeleteOfValue(Seqlist* sq, ElemType value)
{
    
    
	if (sq == NULL) return -1;
	int j = -1;
	for (int i = 0; i < sq->cur_size; i++)
	{
    
    
		if (sq->data[i] != value)
		{
    
    
			j++;
			sq->data[j] = sq->data[i]; 
		}
	}
	sq->cur_size = j + 1;
	return 0;
}

//查找数据
int SearchOfValue(Seqlist* sq, ElemType value)
{
    
    
	if (sq == NULL) return -1;
	for (int i = 0; i < sq->cur_size; i++)
	{
    
    
		if (value == sq->data[i])
		{
    
    
			return i;
		}
	}
	return -1;
}

void FreeSeqList(Seqlist* sq)
{
    
    
	if (sq == NULL) return;
	if (sq->data != NULL)
	{
    
    
		delete sq->data;
		sq->data = NULL;
	}
	sq->all_size = sq->cur_size = 0;
}
void ShowSeqlist(Seqlist* sq)
{
    
    
	if (sq == NULL) return;
	for (int i = 0; i < sq->cur_size; i++)
	{
    
    
		printf("%-4d", sq->data[i]);
	}
	printf("\n");
}


int main()
{
    
    
	Seqlist sq;
	Init_Seqlist(&sq);
	for (int i = 0; i < 20; i++)
	{
    
    
		Insert(&sq, i, i);
	}
	ShowSeqlist(&sq);
	DeleteOfValue(&sq, 18);
	
	printf("%d\n", SearchOfValue(&sq, 19));
	ShowSeqlist(&sq);
	Insert(&sq, 66, 10);
	ShowSeqlist(&sq);
	FreeSeqList(&sq);
	return 0;
}

输出结果:
在这里插入图片描述

总结:扩容注意在数据转移后将原空间释放,防止内存泄漏。

猜你喜欢

转载自blog.csdn.net/xiaoxiaoguailou/article/details/120769273