//顺序表
/*
数据结构 = 结构定义 + 结构操作
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);
}
03-11
7137
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)