复习数据结构,编程线性表的插入和删除操作测试程序,对指针的用法有了新的体会:
课本上对指针的使用是采用了引用的方式,即用&找到指针的位置,对指针所指内容进行修改,我采用的是直接修改线性表,感觉这种方式更简单一些,不知理解是否正确,但程序测试没问题。
#include <iostream>
using namespace std;
#define INIT_LIST_SIZE 100 //初始线性表大小为100
#define LIST_INCREASE 10 //每次扩充线性表长度为10
typedef struct
{
int* pelem; //线性表基址
int n; //当前线性表元素个数
int nListsize; //线性表的存储容量
}CSqlist;
//新建空白表
bool Init_List(CSqlist &L)
{
L.pelem = (int*)malloc(INIT_LIST_SIZE * sizeof(int));//分配地址空间
if (!L.pelem) //存储分配失败
{
cout << "地址分配失败!" << endl;
exit(OVERFLOW);
}
else
{
L.n = 0; //初始线性表长度为0
L.nListsize = INIT_LIST_SIZE; //初始线性表的容量为100
return true;
}
}
/*
[函数名称] Insert
[函数功能] 往线性表中的第index位置插入元素e
[函数参数] CSqlist& L, int index, int e
[函数返回值] 插入成功返回true,插入失败返回false
*/
bool Insert(CSqlist& L, int index, int e)
{
if (index<1 || index>L.n + 1)
{
cout << "插入位置有误!插入失败!" << endl;
return false;
}
//存储空间已满
if (L.n >= L.nListsize)
{
int* pnewbase = (int*)realloc(L.pelem,
(L.nListsize + LIST_INCREASE) * sizeof(int));
if (!pnewbase) //基址分配失败
exit(OVERFLOW);
L.pelem = pnewbase; //新基址
L.nListsize += LIST_INCREASE; //改变线性表的当前容量
}
//index位置后的元素都要后移
for (int i = L.n - 1; i >= index - 1; i--)
{
L.pelem[i + 1] = L.pelem[i];
}
L.pelem[index - 1] = e;//插入新元素
L.n++;//线性表元素个数+1
return true;
}
/*
[函数名称] Delete
[函数功能] 从线性表中删除第index个元素,并将该元素储存在ntmpx中
[函数参数] CSqlist &L,int index,int &ntempx
[函数返回值] 当删除成功时返回true,否则返回false
*/
bool Delete(CSqlist& L, int index, int& ntempx)
{
//判断删除位置是否合法
if (index<1 || index>L.n)
{
cout << "待删除元素位置有误,删除失败!" << endl;
return false;
}
//从index位置往后元素都向前移动
for (int i = index - 1; i <= L.n - 1; i++)
{
L.pelem[i] = L.pelem[i + 1];
}
L.n--; //线性表元素个数减一
return true;
}
/*
[函数名称] ShowList
[函数功能] 显示线性表
[函数参数] CSqlist L
[函数返回值] 空
*/
void ShowList(CSqlist L)
{
for (int i = 0; i < L.n; i++)
{
cout << L.pelem[i] << " ";
}
cout << endl;
}
int main()
{
CSqlist cL;
if (Init_List(cL))
cout << "建立空白线性表成功!" << endl;
if (Insert(cL, 1, 2))
cout << "插入元素成功!" << endl;
ShowList(cL);
if(Insert(cL,3,2))
cout << "插入元素2成功!" << endl;
if(Insert(cL, 2, 3))
cout << "插入元素3成功!" << endl;
ShowList(cL);
int x = 0;
if (Delete(cL, 1, x))
cout << "删除元素1成功!" << endl;
ShowList(cL);
return 0;
}