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

数据结构——顺序表初操作

2016-03-21 20:54 411 查看
利用线性表实现以下操作

(1)初始化顺序表L;

(2)采用尾插法一次插入a,b,c,d,e.元素;

(3)输出顺序表L;

(4)输出顺序表L的长度;

(5)判断顺序表是否为空;

(6)输出顺序表L的第三个元素;

(7)输出元素a的位置;

(8)在第四个元素位置上插入f;

(9)输出顺序表L’

(10)删除L的第三个元素;

(11)输出顺序表L;

(12)释放顺序表L;

源代码

#include <iostream>
#include<malloc.h>
#include<stdio.h>
#define MaxSize 50
using namespace std;
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
} SqList;
extern void InitList(SqList *&L);
extern void DestroyList(SqList *L);
extern bool ListEmpty(SqList *L);
extern int ListLength(SqList *L);
extern void DisPList(SqList *L);
extern bool GetElem(SqList *L,int i,ElemType &e);
extern int LocateElem(SqList *L,ElemType e);
extern bool ListInsert(SqList *&L,int i,ElemType e);
extern bool ListDelete(SqList *&L,int i,ElemType &e);
int main()
{
SqList *L;
ElemType e;
cout<<"顺序表得基本操作如下:"<<endl;
cout<<"(1)初始化顺序表:"<<endl;
InitList(L);
cout<<"(2)依次采用尾插法插入a,b,c,d,e元素:"<<endl;
ListInsert(L,1,'a');
ListInsert(L,2,'b');
ListInsert(L,3,'c');
ListInsert(L,4,'d');
ListInsert(L,5,'e');
cout<<"(3)输出线性表:";
DisPList(L);
cout<<"(4)顺序表长度:"<<ListLength(L)<<endl;
printf("(5)顺序表L为%s\n",(ListEmpty(L)?"空":"非空"));
GetElem(L,3,e);
cout<<"(6)顺序表的第三个元素是:"<<e<<endl;
cout<<"(7)元素a的位置:"<<LocateElem(L,'a')<<endl;
cout<<"(8)在第四个元素位置插入f元素:"<<endl;
ListInsert(L,4,'f');
cout<<"(9)输出顺序表:"<<endl;
DisPList(L);
cout<<"(10)删除L的第三个元素:"<<endl;
ListDelete(L,3,e);
cout<<"(11)输出顺序表:"<<endl;
DisPList(L);
cout<<"(12)释放顺序表:"<<endl;
DestroyList(L);
return 0;
}
void InitList(SqList *&L)
{
L=(SqList *)malloc(sizeof(SqList));
L->length=0;
}
void DestroyList(SqList *L)
{
free(L);
}
bool ListEmpty(SqList *L)
{
return (L->length==0);
}
int ListLength(SqList *L)
{
return (L->length);
}
void DisPList(SqList *L)
{
int i;
if (ListEmpty(L)) return;
for(i=0;i<L->length;i++)
cout<<L->data[i]<<endl;
}
bool GetElem(SqList *L,int i,ElemType &e)
{
if(i<1||i>L->length)
return false;
e=L->data[i-1];
return true;
}
int LocateElem(SqList *L,ElemType e)
{
int i=0;
while(i<L->length&&L->data[i]!=e)
i++;
if(i>=L->length)
return 0;
else
return i+1;
}
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,ElemType &e)
{
int j;
if(i<1||i>L->length)
return false;
i--;
e=L->data[i];
for(j=i;j<L->length-1;j++)
L->data[j]=L->data[j+1];
L->length--;
return true;
}
运行结果

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