#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
#define ElemType int
#define MAXSIZE 100
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef struct{ //结构体
int data[MAXSIZE];
int length;
}Sqlist,*SqList;
//建立顺序表
void CreateList(SqList &L){
L= new Sqlist;
cout<<"请输入建立顺序表的长度:";
int len;
cin>>len;
int i=0;
while(i<len){
cout<<"请输入第"<<i+1<<"个元素:";
ElemType elem;
cin>>elem;
L->data[i]=elem;
i++;
}
L->length=i;//此长度为物理长度
}
//初始化线性表
void InitList(SqList &L){
L=new Sqlist;
L->length=0;
}
//销毁线性表
void DestroyList(SqList &L){
delete(L);
}
//判断是否为空表
bool ListEmpty(SqList L){
return(L->length==0);
}
//输出线性表
void PrintList(SqList L){
int i;
cout<<"输出 ";
for(i=0;i<L->length;i++){
cout<<L->data[i]<<" ";
}
}
//求线性表长度
int ListLength(SqList L){
return(L->length);
}
//求线性表中某个数据的逻辑位置
int GetElemLocation(SqList L){
cout<<"请输入你要查找的元素:";
ElemType elem;
int i=0;
while(i<=L->length-1&&L->data[i]!=elem){
i++;
}
if(i>L->length-1){
return -1;
}else{
return i+1;//转换为逻辑位置
}
}
//按根据位置查找元素
ElemType GetElem(SqList L){
cout<<"请输入你元素位置:";
int location;
cin>>location;
location=location-1;
return L->data[location];
}
//插入数据元素
bool InsertList(SqList &L){
cout<<"请输入你要插入的位置:";
int location;
cin>>location;
location--;//转化为物理位置
if(location<0||location>L->length-1||L->length>=MAXSIZE-1){
return false;
}
int i;
for(i=L->length;i>location;i--){
L->data[i]=L->data[i-1];
}
cout<<"请输入你要插入的元素:";
ElemType elem;
cin>>elem;
L->data[i]=elem;
L->length++;
return true;
}
//删除指定位置数据元素
bool DeleteList(SqList &L){
cout<<"请输入你要删除的位置:";
int location;
cin>>location;
if(location<1||location>L->length){
return false;
}
location--;//将顺序表逻辑序号转化成物理序号
for(int j=location;j<L->length-1;j++){
L->data[j]=L->data[j+1];
}
L->length--;
return true;
}
//主函数
int main(){
SqList L;
InitList(L);
CreateList(L);
cout<<endl;
PrintList(L);
cout<<endl;
int length = ListLength(L);
cout<<"长度为:"<<length;
cout<<endl;
InsertList(L);
PrintList(L);
cout<<endl;
DeleteList(L);
PrintList(L);
cout<<endl;
//其他操作可以自己试一试
return 0;
}
(数据结构)(C++)顺序表的建立和部分基本操作
于 2023-07-04 20:43:27 首次发布