1. 初始化顺序表L。
2. 依次插入a,b,c,d,e元素。
3. 输出顺序表L。
4. 输出顺序表L的长度。
5.输出顺序表L 的第3个元素。
6.输出元素C的位置。
7.在第4个元素位置处插入f元素。
8.删除顺序表L的第3 个元素。
#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;
typedef char ElemType;
#define Maxsize 50
typedef struct
{
ElemType data[Maxsize];
int length;
}SqList;
void InitList(SqList *&L) //初始化线性表
{
L=(SqList *)malloc(sizeof(SqList)); //分配存放线性表的空间
L->length=0; //置空线性表长度为0
}
bool ListEmpty(SqList *L) //判断线性表是否为空
{
return (L->length==0);
}
int ListLength(SqList *L) //求线性表的长度
{
return (L->length);
}
void DispList(SqList *L) //输出线性表
{
int i;
if(L->length==0) return;
for(i=0;i<L->length;i++)
printf("%c ",L->data[i]);
printf("\n");
}
bool GetElem(SqList *L,int i,ElemType &e) //求线性表中某个元数的值
{
if(i<1||i>L->length)
return false;
e=L->data[i];
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)
{
if(i<1||i>L->length)
return false;
i--;
e=L->data[i];
for(;i<L->length-1;i++)
{
L->data[i]=L->data[i+1];
}
L->length--;
return true;
}
int main()
{
SqList *L;
ElemType e;
cout<<"(1)初始化顺序表L:"<<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)输出顺序表L:"<<endl;
DispList(L);
cout<<"(4)顺序表L长度为:"<<ListLength(L)<<endl;
GetElem(L,2,e) ;
cout<<"(5)顺序表L的第3个元素是:"<<e <<endl;
cout<<"(6)元素c的位置:"<<LocateElem(L,'c')<<endl;
cout<<"(7)在第4个元素位置上插入f元素:"<<endl;
ListInsert(L,4,'f');
DispList (L);
cout<<"(8)删除h的第3个元素:"<<endl;
ListDelete(L,3,e);
DispList(L);
}
运行截图