复习数据结构时把6年前自己读代码写的分析再读一遍,收获颇多
源码内容:建立一个链表并且对其进行“插入值”和“删除值”
· 链表的基本分析 ·
//链表的默认大小
const int Capacity = 1024;
template <typename T>
class arrayList
{
public:
//建立链表,定义初始化
arrayList();
//判空
bool empty() const;
//链表大小,结点个数
int size() const;
//在pos处添加值item
void insert(T item, int pos);
//删除pos处的值
void erase(int pos);
//重载“<<”输出符
friend ostream &operator<<(ostream &out, const arrayList &aList);
private:
//输入实际大小
int mySize;
//私有变量建立默认大小的链表
T myArray[Capacity];
};
//初始化定义实际大小
arrayList::arrayList() : mySize(0)
{
}
//判空,大小为0为false
bool arrayList::empty() const
{
return mySize == 0;
}
//赋值实际大小
int arrayList::size() const
{
return mySize;
}
//输出操作符重载
ostream &operator<<(ostream &out, const List &aList)
{
for (int i = 0; i < mySize; i++)
out << alist.myArray[i] << " ";
return out;
}
== == == == == == == == == == == == == == == == == == == =
//输出的举例
void arrayList::display(ostream & out) const
{
for (int i = 0; i < mySize; i++)
out << myArray[i] << " ";
}
ostream &operator<<(ostream &out, const List &aList)
{
aList.display(out);
return out;
}
== == == == == == == == == == == == == == == == == == == =
//插入值
void List::insert(T item, int pos)
{
//如果实际大小等于默认大小就会由于插不进去抛错
if (mySize == Capacity)
{
//引用D_select.h的头文件
cerr << "*** No space for list element -- terminating "
"execution ***\n";
exit(1);
}
//再判断插入位置是否有问题/抛错
if (pos < 0 || pos > mySize)
{
cerr << "*** Illegal location to insert -- " << pos
<< ". List unchanged. ***\n";
return;
}
//从后开始检测
for (int i = mySize; i > pos; i--)
{
//每个元素往后移动一位,将pos位处腾空
myArray[i] = myArray[i - 1];
}
//把值放进pos处
myArray[pos] = item;
//更改实际大小的数值
mySize++;
}
//删除pos位置的值
void arrayList::erase(int pos)
{
//判空提示
if (mySize == 0)
{
cerr << "*** List is empty ***\n";
return;
}
//检测位置抛错
if (pos < 0 || pos >= mySize)
{
cerr << "Illegal location to delete -- " << pos
<< ". List unchanged. ***\n";
return;
}
//直接找到这个位置,然后循环处理,每后边的一个数值往前提一位,直接覆盖了原数值以便达到要求
for (int i = pos; i < mySize; i++)
myArray[i] = myArray[i + 1];
//改变实际大小的数值
mySize--;
}