最近打算复习巩固一下数据结构,用c++实现了顺序表的一些基本功能,可能有bug,有问题的话,希望大佬留下评论指证。
#include <iostream>
#include <cstdlib>
#include <malloc.h>
using namespace std;
//5个常量定义
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
//类型定义
typedef int ElmeType;
typedef int status;
// 定义顺序栈
typedef struct
{
ElmeType *elme;
int length;
int size;
int increment;
} SqlLsit;
//初始化顺序表
status InitSqlList(SqlLsit &L, int size, int inc)
{
L.elme = (ElmeType *) malloc(size * sizeof(ElmeType));
if(L.elme == NULL)
return OVERFLOW;
L.length = 0;
L.size = size;
L.increment = inc;
return OK;
}
//删除顺序表
status DeleteSqlList(SqlLsit &L)
{
free(L.elme);
L.elme = NULL;
L.length = 0;
return OK;
}
//清空顺序表
void ClearSqlList(SqlLsit &L)
{
if(L.length != 0)
L.length = 0;
}
//检测顺序表是否为空
void isEmpty(SqlLsit &L)
{
if(L.length != 0)
cout << "顺序表不为空!\n";
else
cout << "顺序表为空!\n";
}
//返回顺序表元素的个数
status ListLength(SqlLsit &L)
{
return L.length;
}
//返回顺序表中第i个元素的值
status GetElme(SqlLsit &L, int i, ElmeType &e)
{
if(i < 0 || i > L.length)
return -1;
else
{
e = L.elme[i - 1];
return OK;
}
}
//在顺序表中查找元素e,返回它出现的第一个位置,不存在返回-1
status SearchSqlList(SqlLsit &L, ElmeType e)
{
int i = 0;
while(i <= L.length - 1 && L.elme[i] != e)
i++;
if(i <= L.length - 1)
return i + 1;
else
return -1;
}
//在顺序表第i个位置插入元素e
status InsertSqlList(SqlLsit &L, int i, ElmeType e)
{
int j;
if(i <= 0 && i > L.length)
return -1;
for(j = L.length - 1; j >= i - 1; j--)
{
L.elme[j + 1] = L.elme[j];
}
L.elme[i - 1] = e;
L.length++;
return OK;
}
//删除顺序表第i个位置的元素
status DeleteElme(SqlLsit &L, int i)
{
int j;
if(i <= 0 || i > L.length)
return -1;
for(j = i - 1; j < L.length; j++)
{
L.elme[j] = L.elme[j + 1];
}
L.length--;
return OK;
}
//顺序表的打印
void SqlLsitPrint(SqlLsit &L)
{
if(L.length == 0)
{
cout << "顺序表为空!\n";
}
else
for(int i = 0; i < L.length; i++)
cout << L.elme[i] << "\t";
cout << endl;
}
int main()
{
SqlLsit L;
int i, j;
int e;
InitSqlList(L, 50, 10);
for (i = 0; i < 6; i++)
L.elme[i] = i;
L.length = 6;
while(true)
{
//DeleteSqlList(L);
SqlLsitPrint(L);
//ClearSqlList(L);
isEmpty(L);
cout << "顺序表大小为:" << ListLength(L) << endl;
cout << "请输入你想查找第几个元素:";
cin >> i;
j = GetElme(L, i, e);
//cout<<j<<endl;
if(j != -1)
cout << "顺序表第" << i << "个元素的值为:" << e << endl;
else
cout << "请输入正确的索引!\n";
cout << "请输入要查找元素的值:";
cin >> i;
j = SearchSqlList(L, i);
if(j != -1)
cout << i << "在顺序表中第" << j << "个位置\n";
else
cout << "该顺序表中没有您要查找的值\n";
cout << "请输入要插入的位置和元素的值:";
cin >> i >> j;
j = InsertSqlList(L, i, j);
if(j != -1)
SqlLsitPrint(L);
else
cout << "请输入正确的插入位置!\n";
cout << "请输入要删除的位置:";
cin >> i;
j = DeleteElme(L, i);
if(j != -1)
SqlLsitPrint(L);
else
cout << "请输入正确的删除索引!\n";
}
return 0;
}