您的位置:首页 > 理论基础 > 数据结构算法

数据结构之顺序表的基本运算

2016-04-02 12:32 791 查看
#include <iostream>
#include <malloc.h>
#include <cstdio>
#include <cstring>
using namespace std;
#define MaxSize 100
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
} SqList;

void InitList(SqList *&L)   //初始化顺序表L
{
L=(SqList *)malloc(sizeof (SqList));
L->length=0;
}

void ListInsert(SqList *&L,ElemType a[],int n)   //采用尾插法依次插入元素a,b,c,d,e
{
for(int i=0; i<n; i++)
L->data[i]=a[i];
L->length=n;
}
void DispList(SqList *L)         //输出顺序表L
{
for(int i=0; i<L->length; i++)
cout<<L->data[i]<<" ";
cout<<endl;
}
int ListLength(SqList *L)      //输出顺序表L的长度
{
return(L->length);
}
bool ListEmpty(SqList *L)      //判断顺序表L是否为空
{
return(L->length==0);
}
void GetElem(SqList *L,int j)    //输出顺序表的第i个元素
{
for(int i=0; i<L->length; i++)
{
if(i==(j-1))
cout<<L->data[i]<<endl;
}
}
void Displocation(SqList *L,ElemType a)  //输出元素a的位置
{
for(int i=0; i<L->length; i++)
{
if(L->data[i]==a)         //找出a的位置
cout<<i+1<<" ";
}
cout<<endl;
}
bool ListInsert(SqList *&L,int i,ElemType e)   //插入数据元素
{
int j;
if(i<1||i>L->length+1)     //逻辑序号化成物理序号
return false;
i--;
for(j=L->length; j>i; j--)
L->data[j]=L->data[j-1];
L->data[i]=e;
L->length++;       //对的话长度+1
return true;
}
bool ListDelete(SqList *&L,int i)    //删除数据元素
{
int j;
if(i<1||i>L->length+1)
return false;
i--;
for(j=i; j<L->length; j++)
L->data[j]=L->data[j+1];
L->length--;               //删除一个元素后长度-1
return true;
}
void DestoryList(SqList *&L)        //销毁顺序表
{
free(L);
}
int main()
{

char a[10];
char b='a';
cout<<"顺序表的基本运算如下:"<<endl;
SqList *L;
InitList(L);
cout<<"已初始化顺序表"<<endl;
cout<<"采用尾插法依次插入元素 ";
gets(a);
ListInsert(L,a,strlen(a));
cout<<"输出顺序表:";
DispList(L);
cout<<"顺序表的长度:"<<ListLength(L)<<endl;
cout<<"顺序表是否为空:";
if(ListEmpty(L))
cout<<"是"<<endl;
else
cout<<"否"<<endl;
cout<<"顺序表L的第三个元素为:";
GetElem(L,3);
cout<<"输出元素"<<b<<"的位置:";
Displocation(L,b);
ListInsert(L,4,'f');
cout<<"已在第4个元素位置上插入元素f"<<endl;
cout<<"输出顺序表:";
DispList(L);
ListDelete(L,3);
cout<<"已删除第3个位置上的元素"<<endl;
cout<<"输出顺序表:";
DispList(L);
DestoryList(L);
cout<<"顺序表已释放!"<<endl;
return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: