1<=i<=length
头文件:
#ifndef ORDERLIST_H_INCLUDED
#define ORDERLIST_H_INCLUDED
#define SetType(x) typedef x ElemType //设置变量类型
typedef struct{
ElemType *data;
int maxsize;
int length;
}SqList;
void InitList(SqList &L, int n); //初始化
void DestroyList(SqList &L); //销毁
int GetLength(SqList &L); //得到长度
ElemType GetElemByIndex(SqList &L, int i); //按位查找
void PrintList(SqList &L); //打印整个顺序表
void Append(SqList &L,ElemType e); //添加一个元素
bool InsertELem(SqList &L, int i, ElemType e); //第i个位置插入
bool DeleteElem(SqList &L, int i); //删除第i个元素
int GetELemByValue(SqList &L, ElemType e); //按值查找,返回第一个
bool IsEmpty(SqList &L); //判断是否为空
#endif // ORDERLIST_H_INCLUDED
函数实现文件
#include"OrderList.h"
#include<iostream>
using namespace std;
/*
初始化顺序表
*/
void InitList(SqList &L, int n){
L.length = 0;
L.maxsize = n;
L.data = new ElemType[n]; //动态分配一个n个元素大小的内存空间
}
/*
求表长
*/
int GetLength(SqList &L){
return L.length;
}
/*
按位查找
*/
ElemType GetElemByIndex(SqList &L, int i){
return L.data[i-1];
}
/*
打印顺序表中所有的元素
*/
void PrintList(SqList &L){
cout<<L.data[0];
for(int i = 1; i < L.length; i ++)
cout<<" "<<L.data[i];
}
/*
添加一个元素
*/
void Append(SqList &L,ElemType e){
L.data[L.length++] = e;
}
/*
将元素e插入到顺序表L的第i个位置
*/
bool InsertELem(SqList &L, int i, ElemType e){
if(i < 1 || i > L.length + 1) // 判断输入是否合法
return false;
if(L.length >= L.maxsize) //判断存储空间是否已满
return false;
//将插入位置以后的元素后移一位
for(int j = L.length; j >= i; j --)
L.data[j] = L.data[j-1];
L.data[i-1] = e; //插入元素
L.length ++; //顺序表长度+1
return true;
}
/*
删除顺序表L第i个位置的元素
*/
bool DeleteElem(SqList &L, int i){
if(i < 1 || i > L.length) //判断输入是否合法
return false ;
//将第i个位置及以后的元素前移
for(int j = i; j < L.length; j ++)
L.data[j-1] = L.data[j];
L.length--; //顺序表长度-1
return true;
}
/*
查找第一个元素值为e的元素,返回其元素位序,否则返回0
*/
int GetELemByValue(SqList &L, ElemType e){
for(int i = 0;i < L.length; i ++)
if(L.data[i] == e)
return i +1;
return 0;
}
/*
判断L是否为空表
*/
bool IsEmpty(SqList &L){
if(L.length == 0)
return true;
else
return false;
}
/*
销毁顺序表
*/
void DestroyList(SqList &L){
delete []L.data;
}