#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
#define MAX_SIZE 100
typedef struct
{
int *elems; //顺序表的基址
int length; //顺序表的长度
int size; //顺序表的空间大小
}SqList;
bool initlist(SqList &L) //创建一个顺序表
{
L.elems = new int[MAX_SIZE]; //分配MAX_SIZE大小的空间
if (!L.elems)
{
return false; //分配失败
}
L.length = 0;
L.size = MAX_SIZE;
return true;
}
void listprint(SqList& L) //打印顺序表元素
{
cout << "顺序表的储存空间size;" << L.size << ",已保存的元素个数length:" << L.length << endl;
for (int i = 0; i <=L.length-1; i++)
{
cout << L.elems[i]<<" ";
}
cout << endl;
}
bool listAppend(SqList& L, int e) //顺序表尾部添加元素
{
if (L.length==L.size)
{
return false;
}
L.elems[L.length] = e;
L.length++;
return true;
}
bool listInsert(SqList& L, int i, int e)//i是插入的位置,在指定位置插入元素
{
if (i<0||i>L.length)
{
return false;
}
if (L.length==L.size)
{
return false;
}
if ((L.length - 1) == i)
{
L.elems[L.length] = e;
L.length++;
return true;
}
for (int j = L.length-1 ; j >= i; j--)
{
L.elems[j + 1] = L.elems[j];
}
L.elems[i] = e;//将元素e放入i的位置
L.length++;//表长加1
return true;
}
bool listDelete(SqList& L, int i)//顺序表指定位置删除元素
{
if (i<0|| i>=L.length)
{
return false;
}
if (i==L.length-1)
{
L.length--;
return true;
}
for (int j = i; j < L.length-1; j++)
{
L.elems[j] = L.elems[j + 1];
}
L.length--;
return true;
}
void destoryList(SqList& L) //顺序表销毁
{
if (L.elems)
{
delete[] L.elems;
L.length = 0;
L.size = 0;
}
}
int main()
{
SqList list;
int e;
int i;
cout << "初始化顺序表" << endl;
if (initlist(list))
{
cout << "初始化顺序表成功!" << endl;
}
listprint(list);
//添加元素
int count = 0;
cout << "请输入要添加的元素个数:" << endl;
cin >> count;
for (int i = 0; i < count; i++)
{
cout << "\n请输入要添加的元素:";
cin >> e;
if (listAppend(list,e))
{
cout << "添加成功!" << endl;
}
else
{
cout << "添加失败!" << endl;
}
}
listprint(list);
//插入元素
cout << "请输入要插入的位置和要插入的数据元素:\n";
cin >> i >> e;
if (listInsert(list, i, e))
{
cout << "插入成功!" << endl;
}
else
{
cout << "插入失败!" << endl;
}
listprint(list);
//删除元素
cout << "请输入要删除元素的位置:";
cin >> i;
if (listDelete(list, i))
{
cout << "删除成功!" << endl;
}
else
{
cout << "删除失败" << endl;
}
listprint(list);
//销毁顺序表
destoryList(list);
return 0;
}