D_S 顺序表的基本操作
// main.cpp
#include <iostream>
using namespace std;
#include "Status.h"
#include "SqList.h"
int main()
{
SqList L;
int n,i;
ElemType e;
InitList(L);
cout<<"\nL=";
ListTraverse(L);
cout<<"\n请设置将向线性表L中输入的元素个数:";
cin>>n;
CreateList(L,n);
cout<<"\nL=";
ListTraverse(L);
cout<<"\nL的表长为:"<<ListLength(L)<<endl;
cout<<"\n请输入想要获取的元素位序:";
cin>>i;
if(GetElem(L,i,e)) cout<<"\n第"<<i<<"个元素为:"<<e<<endl;
else cout<<"\n第"<<i<<"个元素不存在!"<<endl;
cout<<"\n请输入要查找的元素:";
cin>>e;
if((i=(LocateElem(L,e)))) cout<<"\n元素"<<e<<"的位置为:"<<i<<endl;
else cout<<"\n元素"<<e<<"不存在!"<<endl;
cout<<"\n请输入插入位置和所插入元素:";
cin>>i>>e;
if(ListInsert(L,i,e))
{
cout<<"\nL=";
ListTraverse(L);
}
else cout<<"\n插入操作失败!"<<endl;
cout<<"\n请输入被删元素的位置:";
cin>>i;
if(ListDelete(L,i,e)) cout<<"\n被删元素为:"<<e<<endl;
else cout<<"\n删除操作失败!"<<endl;
cout<<"\nL=";
ListTraverse(L);
}
// Status.h
#ifndef yuan_Status_h
#define yuan_Status_h
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
#endif
// SqList.h
#ifndef yuan_SqList_h
#define yuan_SqList_h
#define MAXSIZE 100
typedef struct{
ElemType *elem;
int length;
}SqList;
Status InitList(SqList &L)
{ //构造一个空的顺序表
L.elem=new ElemType[MAXSIZE]; //为顺序表分配一个大小为MAXSIZE的数组空间
if(!L.elem) exit(OVERFLOW); //存储分配失败
L.length=0; //空表长度为0
return OK;
}
Status CreateList(SqList &L,int n)
{
int i;
if(!L.elem||n<0||n>MAXSIZE) return ERROR;
cout<<"\n请输入"<<n<<"个元素:";
for(i=1;i<=n;i++)
cin>>L.elem[i-1]; //可以用随机函数rand()自动生成
L.length=n;
return OK;
}
void ListTraverse(SqList L)
{
int i;
cout<<'(';
for(i=1;i<=L.length;i++)
cout<<L.elem[i-1]<<',';
if(L.length) cout<<"\b)"<<endl;
else cout<<')'<<endl;
}
Status ListLength(SqList L){
return L.length;
}
Status ListInsert(SqList &L,int i,ElemType e)
{
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];
L.elem[i-1]=e;
++L.length;
return OK;
}
Status ListDelete(SqList &L,int i,ElemType &e)
{
if(i<1||i>L.length) return ERROR;
e=L.elem[i-1];
for (int j=i;j<=L.length-1;j++)
L.elem[j-1]=L.elem[j];
--L.length;
return OK;
}
Status GetElem(SqList L,int i,ElemType &e)
{
if(i<0||i>L.length) return ERROR;
e=L.elem[i-1];
return e;
}
Status LocateElem(SqList L,ElemType e)
{
for (int i=0; i<L.length; i++)
if (L.elem[i]==e) return i+1;
return 0;
}
#endif