数据结构 顺序表
今天尝试实现顺序表,基本的增,删,查,插,改功能基本实现,但扩容时存在部分问题,只能部分扩容,原因尚未找出,等待后续优化(鬼晓得什么时候,也许明天)
2023.11.11 今天提交链表顺便修复一下之前的bug,扩容时忘了size++
代码如下(博客显示有点问题,不知道为什么,之后去修复一下)
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdexcept>
using namespace std;
template<class T>
class ArrayList
{
public:
ArrayList(int Num) :size(0) //初始化构造函数
{
date = new T[Num];
if (date == nullptr)
{
cout << "开辟失败" << endl;
}
length = Num;
}
void AddEle(T ele)//增添元素
{
//判断是否超过最大容量
try
{
if (size <length)
{
date[size] = ele;
size++;
}
else
{
throw runtime_error("空间已满,是否扩容 Y/N");
}
}
catch (runtime_error err)
{
cout << err.what() << endl;
char ch(0);
cin >> ch;
if (ch == 'Y' || ch == 'y')
{
T* date_copy = new T[size + 1];
for (size_t i = 0; i < length; i++)
{
date_copy[i] = date[i];
}//将值存储到新空间
delete[] date;
if (date != nullptr)
{
date = nullptr;
}
date = date_copy;
date_copy = nullptr;
length++;
date[length - 1] = ele;
size++;
}
else
{
cout << "不进行扩容,无法增添新元素" << endl;
return;
}
}
}
int FindEle(T ele)//查找元素
{
for (size_t i = 0; i < size; i++)
{
if (date[i] == ele)
{
return i;
}
}
return -1;
}
void DelEle(T ele)
{
int index = FindEle(ele);
if (index == -1)
{
cout << "查无此元素" << endl;
}
else
{
for (size_t i = index + 1; i < size; i++)
{
date[i - 1] = date[i];
}
size--;
}
}
void InsertEle( T ele, int index_)
{
//判断是否超过最大容量
try
{
if (size < length)
{
for (size_t i = size; i > index_; i--)
{
date[i] = date[i - 1];
}
date[index_] = ele;
size++;
}
else
{
throw runtime_error("空间已满,是否扩容 Y/N");
}
}
catch (runtime_error err)
{
cout << err.what() << endl;
char ch(0);
cin >> ch;
if (ch == 'Y' || ch == 'y')
{
T* date_copy = new T[size + 1];
for (size_t i = 0; i < length; i++)
{
date_copy[i] = date[i];
}//将值存储到新空间
delete[] date;
if (date != nullptr)
{
date = nullptr;
}
date = date_copy;
date_copy = nullptr;
length++;
date[length - 1] = ele;
size++;
}
else
{
cout << "不进行扩容,无法增添新元素" << endl;
return;
}
}
}
void ChangeEle(T ele, int index_)
{
date[index_] = ele;
}
public:
T* date; //指针模拟数组
int length; //理论最大容量
int size; //实际大小
};
int main()
{
ArrayList<int> myarr(10);
myarr.AddEle(10);
myarr.AddEle(11);
myarr.AddEle(12);
myarr.AddEle(13);
myarr.AddEle(14);
myarr.InsertEle(15, 5);
myarr.AddEle(16);
myarr.AddEle(17);
cout << myarr.FindEle(11) << endl;
myarr.DelEle(16);
for (size_t i = 0; i < myarr.size; i++)
{
cout << myarr.date[i] << ' ';
}
return 0;
}