问题及代码
编写一个程序exp2-1.cpp,实现顺序表的各种运算(假设顺序表的元素类型为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<stdio.h>
#include<malloc.h>
#define SizeMax 50
using namespace std;
typedef char ElemType;
typedef struct
{
ElemType data[SizeMax];
int length;
} SqList;
void InitList(SqList *&L)//初始化顺序表
{
printf("(1)初始化顺序表L\n");
L=(SqList *)malloc(sizeof(SqList));
L->length=0;
}
void Insert(SqList *L,ElemType x)
{
L->data[L->length]=x;
L->length++;
}
void Print(SqList *L)
{
int i;
for(i=0; i<L->length; i++)
printf("%c ",L->data[i]);
printf("\n");
}
void PrintLength(SqList *L)
{
printf("(4)顺序表长度为%d\n",L->length);
}
bool SqNull(SqList *L)
{
if(L->length==0)
return false;
else
return true;
}
bool PrintData(SqList *L,int n)
{
if(n<0||n>L->length)
return false;
printf("(6)顺序表L的第%d个元素=%c\n",n,L->data[n-1]);
return true;
}
int find(SqList *L,ElemType x)
{
int i;
for(i=0; i<L->length; i++)
if(L->data[i]==x)
return i+1;
}
bool Insertinto(SqList *L,int i,ElemType x)
{
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]=x;
L->length++;
return true;
}
bool Delete(SqList *&L,int i)
{
int j;
if(i<1||i>L->length+1)
return false;
i--;
for(j=i; j<L->length-1; j++)
L->data[j]=L->data[j+1];
L->length--;
return true;
}
int main()
{
SqList *L;
InitList(L);
ElemType a,b,c,d,e;
printf("(2)依次采用尾插法插入a,b,c,d,e元素:");
scanf("%c %c %c %c %c%*c",&a,&b,&c,&d,&e);
Insert(L,a);
Insert(L,b);
Insert(L,c);
Insert(L,d);
Insert(L,e);
printf("(3)输出顺序表L:");
Print(L);
PrintLength(L);
if(SqNull(L))
printf("(5)顺序表L为非空\n");
else printf("(5)顺序表L为空\n");
PrintData(L,3);
printf("(7)元素a的位置=%d\n",find(L,a));
printf("(8)在第4个元素位置上插入元素f:");
ElemType f;
scanf("%c",&f);
Insertinto(L,4,f);
printf("(9)输出顺序表L:");
Print(L);
printf("(10)删除L的第3个元素\n");
Delete(L,3);
printf("(11)输出顺序表L:");
Print(L);
printf("(12)释放顺序表\n");
free(L);
return 0;
}
运算结果