顺序表|数据结构

认识数据结构

1. 什么是数据结构?

数据结构(Data Structure)是计算机存储、组织数据的方式,指相互之间存在一种或多种特定关系的数据元素的集合。

2.什么是算法?

算法(Algorithm):就是定义良好的计算过程,他取一个或一组的值为输入,并产生出一个或一组值作为
输出。简单来说算法就是一系列的计算步骤,用来将输入数据转化成输出结果。

数据结构入门练手

1、顺序表

顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改

顺序表一般可以分为:
1. 静态顺序表:使用定长数组存储元素。
在这里插入图片描述
就是一个比较局限大小,对于后面使用就比较局限使用。
2. 动态顺序表:使用动态开辟的数组存储。

在这里插入图片描述

静态顺序表只适用于确定知道需要存多少数据的场景。静态顺序表的定长数组导致N定大了,空间开多了浪费,开少了不够用。所以现实中基本都是使用动态顺序表,根据需要动态的分配空间 大小,所以下面我们实现动态顺序表。

2、实现动态顺序表

对于数据结构里使用比较多无非是增删插找。可以一一实现这些接口。

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
//
typedef int SLDataType;

typedef struct SeqList
{
    
    
	SLDataType* a;
	int size;       // 记录存储多少个有效数据
	int capacity;   // 空间容量大小 
}SL;

//打印
void SLPrint(SL* ps);
//初始化
void SLInit(SL* ps);
//销毁
void SLDestroy(SL* ps);
//尾插
void SLPushBack(SL* ps, SLDataType x);
//尾删
void SLPopBack(SL* ps);
// 头插头删
void SLPushFront(SL* ps, SLDataType x);
void SLPopFront(SL* ps);

函数实现

void SLPrint(SL* ps)
{
    
    
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
    
    
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

void SLInit(SL* ps)
{
    
    
	assert(ps);
	ps->a = NULL;
	ps->capacity = 0;
	ps->size = 0;
}

void SLDestroy(SL* ps)
{
    
    
	assert(ps);
	if (ps->a)
	{
    
    
		free(ps->a);
		ps->capacity = 0;
		ps->size = 0;
	}
}


void SLPushBack(SL* ps, SLDataType x)
{
    
    
	assert(ps);
	//检查空间是否足够
	if (ps->size == ps->capacity)
	{
    
    
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLDataType* temp = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType));
		if (temp == NULL)
		{
    
    
			perror("realloc fail");
			exit(-1);
		}
		ps->a = temp;
		ps->capacity=newcapacity;
	}
	ps->a[ps->size] = x;
	ps->size++;
}

void SLPopBack(SL* ps)
{
    
    
	assert(ps);
	if (ps->size>0)
		ps->size--;
}

void SLPushFront(SL* ps, SLDataType x)
{
    
    
	int end = ps->size - 1;
	while (end>=0)
	{
    
    
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
}

void SLPopFront(SL* ps)
{
    
    
	assert(ps->size>0);
	//头删需要注意大小,空表头出现
	int begin = 1;
	while (ps->size > begin)
	{
    
    
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;
}

总结

顺序表和数组离不开,这就意味着它对于空间要求比较大,伴随这一些增容需要申请新空间,拷贝数据,释放旧空间。会有不小的消耗。
增容一般是呈2倍的增长,势必会有一定的空间浪费。例如当前容量为100,满了以后增容到200,我们再继续插入了5个数据,后面没有数据插入了,那么就浪费了95个数据空间。空间浪费比较多。

猜你喜欢

转载自blog.csdn.net/github_73587650/article/details/128096563