数据结构顺序表

#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int DataType;

typedef struct SeqList
{	
	DataType* data;
	int size;//当前大小
	int capacity;//最大容量
}SL;

void init(SL* pl);//初始化
void clear(SL* pl);//清空
void destroy(SL* pl);//销毁
void print(SL* pl);//打印
void check(SL* pl);//检查是否溢出
void addLast(SL* pl, DataType x);//添加
void add(SL* pl, int idx, DataType x);//索引添加
DataType removeLast(SL* pl);//删除
DataType remove(SL* pl, int idx);//索引删除
DataType getLast(SL* pl);//查询数据
DataType get(SL* pl, int idx);//查询数据
int find(SL* pl, DataType x);//查询索引
void set(SL* pl, int idx, DataType x);//修改
int isEmpty(SL* pl);//判空
int size(SL* pl);//获取大小
#include "SeqList.h"


void init(SL* pl)
{
	assert(pl);
	pl->data = (DataType*)malloc(sizeof(DataType) * 4);//初始化4个大小空间
	//初始化失败
	if (pl->data == NULL)
	{
		printf("失败");
		exit(-1);
	}
	pl->size = 0;
	pl->capacity = 4;//初始容量
}

void clear(SL* pl)
{
	assert(pl);
	init(pl);
}

void destroy(SL* pl)
{
	assert(pl);
	free(pl->data);
	free(pl);
}

void print(SL* pl)
{
	assert(pl);//判断是否为null
	for (int i = 0; i < pl->size; i++)
	{
		printf("%d ", pl->data[i]);
	}
	printf("\n");
}

void check(SL* pl)
{
	assert(pl);
	if (pl->size == pl->capacity)
	{
		pl->capacity = pl->capacity * 2;
		pl->data = (DataType*)realloc(pl->data, sizeof(DataType) * pl->capacity);//获取两倍空间
		if (pl->data == NULL)
		{
			printf("失败");
			exit(-1);
		}
	}
}

void addLast(SL* pl, DataType x)
{
	assert(pl);
	check(pl);
	add(pl, pl->size, x);
}

void add(SL* pl, int idx, DataType x)
{
	assert(pl);
	assert(idx <=pl->size&& idx>=0);
	check(pl);
	int end = pl->size - 1;
	//向后移动
	while (end >= idx)
	{
		pl->data[end + 1] = pl->data[end];
		end--;
	}
	pl->data[idx] = x;
	pl->size++;
}

DataType removeLast(SL* pl)
{
	assert(pl);
	return remove(pl, pl->size - 1);
}

DataType remove(SL* pl, int idx)
{
	assert(pl);
	assert(idx < pl->size&& idx >= 0);
	DataType ans = pl->data[idx];
	int start = idx;
	//向前移动
	while (start <= pl->size - 2)
	{
		pl->data[start] = pl->data[start + 1];
		start++;
	}
	pl->size--;
	return ans;
}

DataType getLast(SL* pl)
{
	assert(pl);
	return get(pl,pl->size - 1);
}

DataType get(SL* pl, int idx)
{
	assert(pl);
	assert(idx < pl->size&& idx >= 0);
	return pl->data[idx];
}

int find(SL* pl, DataType x)
{
	assert(pl);
	for (int i = 0; i < pl->size; i++) {
		if (pl->data[i] == x)
			return i;
	}
	return -1;
}

void set(SL* pl, int idx, DataType x)
{
	assert(pl);
	assert(idx < pl->size&& idx >= 0);
	pl->data[idx] = x;
}

int isEmpty(SL* pl)
{
	return pl->size == 0 ? 1 : 0;
}

int size(SL* pl)
{
	return pl->size;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值