#include<iostream>
#include<string>
#include<cmath>
using namespace std;
#define MaxSize 100
#define OK 1
#define FLASE 0
#define OVER -1
typedef char Elemtype;
typedef int Status;
//顺序表类型
typedef struct
{
Elemtype* elem;
int length;
}SqList;
//线性表L的初始化
Status InitList_Sq(SqList& L)
{
L.elem = new Elemtype[MaxSize];
if (!L.elem) exit(OVER);
L.length = 0;
return OK;
}
//销毁线性表L
void DestoryList(SqList& L)
{
if (L.elem) delete L.elem;
}
//清空线性表
void ClearList(SqList& L)
{
L.length = 0;
}
//求线性表L的长度
int GetLength(SqList L)
{
return L.length;
}
//判断线性表是否为空
int isEmpty(SqList L)
{
if (L.length == 0) return 1;
else return 0;
}
//线性表的取值(根据位置求内容)
int GetElem(SqList L, int i, Elemtype& e)
{
if (i<1 || i>L.length)return FLASE;
e = L.elem[i - 1];
return OK;
}
//查找该值e的位置
int LocateElem(SqList L, Elemtype e)
{
int i;
for (i = 0; i < L.length; i++)
{
if (L.elem[i] == e) return i + 1;
}
return 0;
}
//显示列表
void ShowList(SqList L)
{
for (int i = 0; i < L.length; i++)
cout << L.elem[i] << " ";
cout << endl;
}
//顺序表的插入
Status ListInsert(SqList& L, int i, Elemtype e)
{
if (i<1 || i>L.length + 1) return OVER;
if (L.length == MaxSize) return OVER;
for (int j = L.length; j >= i - 1; j--)
{
L.elem[j + 1] = L.elem[j];
}
L.elem[i - 1] = e;
L.length++;
return OK;
}
//顺序表的删除
Status ListDelete(SqList& L, int i)
{
if (i<1 || i>L.length) return OVER;
for (int j = i; j <= L.length - 1; j++)
L.elem[j - 1] = L.elem[j];
L.length--;
return OK;
}
int main()
{
SqList L;
InitList_Sq(L); //L初始化
cout << InitList_Sq(L)<< endl;
if (isEmpty(L) == 1) //判断是否为空
{
cout << "L为空!" << endl;
}
ListInsert(L, 1, 'a'); //添加数据
ListInsert(L, 2, 'b');
ListInsert(L, 3, 'c');
ShowList(L);
int Length = GetLength(L);
cout << "长度为:" << Length << endl;
char data; GetElem(L, 2, data); //求i=2的数据
cout << data << endl;
cout << LocateElem(L, 'c') << endl; //求数据 b 的位置
cout << "数据长度为:" << GetLength(L)<<endl;
ListDelete(L, 1);
char data1; GetElem(L, 1, data1); //求i=1的数据
cout << data1 << endl;
ClearList(L);
int Length1 = GetLength(L);
cout << "长度为:" << Length1 << endl;
}
顺序表代码
于 2024-11-14 22:12:15 首次发布