顺序表操作(C++)(实验一):
#include <iostream>
#define MAXSIZE 100
using namespace std;
//顺序表的结构体
typedef struct SqList{
int *elem;
int length;
}Sqlist;
//顺序表的初始化
void InitList(Sqlist &L){
L.elem = new int[MAXSIZE];
L.length = 0;
}
//插入数据
void ListInsert(Sqlist &L, int loc, int e){
if(loc<1 || loc>L.length+1 || L.length==MAXSIZE){
cout<<"非法操作\n";
return ;
}
else
{
for(int i=L.length-1; i>=loc-1; i--){
L.elem[i+1] = L.elem[i];
}
L.elem[loc-1] = e;
L.length++;
return ;
}
}
//查找
int LocateElem(Sqlist L, int elem){
for(int i=0; i<L.length; i++){
if(L.elem[i]==elem)
return i+1;
}
return -1;
}
//删除某个元素
void ListDelete(Sqlist &L, int loc){
if(loc<1 || loc>L.length ){
cout<<"非法操作"<<endl;
return ;
}
else{
for(int i=loc; i<=L.length; i++){
L.elem[i-1] = L.elem[i];
}
L.length--;
return ;
}
}
//判空
bool IsEmpty(Sqlist L){
if(L.length==0)
return true;
else
return false;
}
//清空
void CleanList(Sqlist &L){
L.length = 0;
}
//返回顺序表长度
int ListLength(Sqlist L){
return L.length;
}
//输出某位置元素的直接前驱
void PreElem(Sqlist L, int loc){
if(loc<=1){
cout<<"非法操作"<<endl;
return ;
}
cout<<"直接前驱:"<<L.elem[loc-2]<<endl;;
return ;
}
//输出某位置元素的直接后继
void NextElem(Sqlist L, int loc){
if(loc>=L.length){
cout<<"非法操作"<<endl;
return ;
}
cout<<"直接后继:"<<L.elem[loc]<<endl;
return ;
}
//打印顺序表
void PrintList(Sqlist L){
for(int i=0; i<L.length; i++){
cout<<L.elem[i]<<endl;
}
}
int main()
{
//创建一个顺序表
Sqlist L;
//初始化顺序表
InitList(L);
//插入数据
ListInsert(L, 1, 1);
ListInsert(L, 1, 2);
ListInsert(L, 1, 3);
ListInsert(L, 1, 4);
ListInsert(L, 1, 5);
ListInsert(L, 1, 6);
ListInsert(L, 1, 7);
//ListInsert(L, 9, 7);ListInsert(L, 0, 7);非法
//查找元素
int loc = LocateElem(L, 6);
if(loc==-1){
cout<<"该元素不存在"<<endl;
}
else
cout<<"位置:"<<loc<<endl;
//查找前驱
PreElem(L, 0);
//查找后继
NextElem(L, 7);
//删除某个元素
//ListDelete(L, 1);
// ListDelete(L, 0); ListDelete(L, 8);非法
//打印顺序表
PrintList(L);
return 0;
}