顺序表(C语言实现)

//顺序表
/*
数据结构 = 结构定义 + 结构操作
1、顺序表的结构定义:数组添加了size和count两种属性
2、顺序表的插入操作:平行向后移动一位,空出位置后,放入元素;改变count
3、顺序表的删除操作:所有元素向前移动,改变count
*/

#include<iostream>
using namespace std;
typedef struct vector {
	int* data;
	int size;
	int count;
}vector;

vector* getNewVector(int size)
{
	vector* v = (vector*)malloc(sizeof(vector));
	v->count = 0;
	v->size = size;
	v->data = (int*)malloc(sizeof(int) * size + sizeof(int));
	return v;
}

void Expand(vector* v)
{
	if (v == NULL)
	{
		printf("顺序表为空,无法扩容\n");
		return;
	}
	cout << "成功将顺序表从" << v->size << "扩容到" << 2 * v->size << endl;
	v->data = (int*)realloc(v->data, sizeof(int) * 2 * v->size + sizeof(int) * v->size);
	v->size = 2 * v->size;
}

void Insert(vector *v, int dat,int pos)
{
	if (pos > v->count + 1)
	{
		throw "无法插入";
		return;
	}
	if (v->count == v->size)
	{
		cout << "顺序表已经满了,无法插入,需要顺序表扩容\n";
		Expand(v);
	}

	for (int i = v->count; i >= pos; i--)
		v->data[i + 1] = v->data[i];
	v->data[pos] = dat;
	v->count++;
	cout << "已经将数据" << dat << ",成功插入到顺序表的位置" << pos << endl;
}

void Delete(vector* v, int pos)
{
	if (pos > v->count)
	{
		throw "无法插入";
		return;
	}
	if (v->count == v->size)
	{
		throw "顺序表已经满了,无法插入";
		return;
	}
	cout << "已经成功删除位置" << pos << "的元素" << v->data[pos] << endl;
	for (int i = pos; i <= v->count; i++)
		v->data[i] = v->data[i + 1];
	v->count--;
}


void print_vector(vector *v)
{
	if (v->count < 1)
		throw"没有元素!无法打印";
	cout << "打印顺序表" << endl;
	for (int i = 1; i <= v->size; i++)
		printf("%-3d ", i);
	cout << endl;
	for (int i = 1; i <= v->count; i++)
	{
		printf("%-3d ", v->data[i]);
	}
	cout << endl;
}

void clear(vector* v)
{
	if (v == NULL)
		return;
	delete v->data;
	delete v;
	return;
}

int main()
{
	vector* v1 = getNewVector(10);
	Insert(v1, 2, 1);
	print_vector(v1);
	Insert(v1, 5, 1);
	print_vector(v1);
	Insert(v1, 41, 2);
	print_vector(v1);
	Delete(v1, 1);
	print_vector(v1);
	Insert(v1, 2, 1);
	print_vector(v1);
	Insert(v1, 5, 1);
	print_vector(v1);
	Insert(v1, 41, 2);
	print_vector(v1);
	Delete(v1, 1);
	print_vector(v1);
	Insert(v1, 2, 1);
	print_vector(v1);
	Insert(v1, 5, 1);
	print_vector(v1);
	Insert(v1, 41, 2);
	print_vector(v1);
	Delete(v1, 1);
	print_vector(v1);
	Insert(v1, 2, 1);
	print_vector(v1);
	Insert(v1, 5, 1);
	print_vector(v1);
	Insert(v1, 41, 2);
	print_vector(v1);
	Delete(v1, 1);
	print_vector(v1);
	Insert(v1, 2, 1);
	print_vector(v1);
	Insert(v1, 5, 1);
	print_vector(v1);
	Insert(v1, 41, 2);
	print_vector(v1);
	Delete(v1, 1);
	print_vector(v1);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值