#pragma once
#include <cstdlib>
#define MAXSIZE 100
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -1
typedef int Status;
typedef char ElementType;
typedef struct {
ElementType* elem;
int length;
}SqList;
Status initList_Sq(SqList& L) {
//为顺序表分配空间
L.elem = new ElementType[MAXSIZE];
//存储分配失败
if (!L.elem) {
exit(OVERFLOW);
}
//空表长度为0
L.length = 0;
return OK;
}
void destroyList_Sq(SqList& L) {
//释放存储空间
if (L.elem)
delete L.elem;
}
void clearList_Sq(SqList& L) {
//将线性表的长度置为0
L.length = 0;
}
int getLength_Sq(SqList L) {
return L.length;
}
int isEmpty_Sq(SqList L) {
if (L.length == 0)
return 1;
else
return 0;
}
//根据位置i获取相应位置数据元素的内容
int getElem_Sq(SqList L, int i, ElementType& e) {
if (i<1 || i>L.length) //判断i的值是否合理
return ERROR;
e = L.elem[i - 1]; //第i-1的单元存储着第i个数据
return OK;
}
int locateElem_Sq(SqList L, ElementType e) {
for (int i = 0; i < L.length; i++) {
//查找成功,返回序号
if (L.elem[i] == e) {
return i + 1;
}
//查找失败,返回0
}
return 0;
}
Status listInsert_Sq(SqList& L, int i, ElementType e) {
//i值不合法
if (i<1 || i>L.length + 1)
{
return ERROR;
}
//当前存储空间已满
if (L.length == MAXSIZE)
{
return ERROR;
}
for (int j = L.length - 1; j >= i - 1; j--) {
L.elem[j + 1] = L.elem[j];
}
//将新元素e放入第i个位置
L.elem[i - 1] = e;
//表长增1
L.length++;
return OK;
}
Status listDelete_Sq(SqList& L, int i, ElementType& e) {
//i值不合法
if (i<1 || i>L.length)
{
return ERROR;
}
//用e返回
e = L.elem[i - 1];
for (int j = i - 1; j < L.length - 2; j++) {
L.elem[j] = L.elem[j + 1];
}
//表长-1
L.length--;
return OK;
}
线性表的顺序表示及实现
猜你喜欢
转载自blog.csdn.net/Warmmm/article/details/112816044
今日推荐
周排行