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

数据结构之顺序表操作

2016-03-21 16:47 393 查看
/*
编写一个程序,实现顺序表的各种基本运算(假设顺序表的元素类型为Char)。
(1)初始化顺序表L;
(2)采用尾插法依次插入元素a,b,c,d,e;
(3)输出顺性表L;
(4)输出顺序表L长度;
(5)判断顺序表L是否为空;
(6)输出顺序表L的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入元素f;
(9)输出顺序表L;
(10)删除L的第3个元素;
(11)输出顺序表L;
(12)释放顺序表L。
*/

#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)
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++;
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--;
return true;
}
void DestoryList(SqList *&L)        //销毁顺序表
{
free(L);
}
int main()
{
char a[10];
char b='a';
gets(a);
SqList *L;
InitList(L);
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;
}


 

运行结果:

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