(2)实现顺序表的各种基本运算

题目:

编写一个程序 algo2-1.cpp,实现顺序表的各种基本运算(假设顺序表的元素类型为 char),并在此基础上设计一个程序 exp2-1,完成如下功能:
( 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;

代码:

#include <stdio.h>
#include <malloc.h>
#define MaxSize 50
typedef char ElemType;
//声明线性表的顺序存储类型
typedef struct
{
	ElemType data[MaxSize];
	int length;
}SqList;
void CreateList(SqList *&L,ElemType a[],int n)
{
	int i=0,k=0;
	L=(SqList *)malloc(sizeof(SqList));
	while(i<n)
	{	L->data[k]=a[i];
		k++,i++;
	}
	L->length=k;
}
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)
{
	for (int 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 0;
	e=L->data[i-1];
	return 1;
}
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 1;
}
bool ListDelete(SqList *&L,int i,ElemType &e)
{
	int j;
	if(i<1 && i>L->length+1)
		return 0;
	i--;
	e=L->data[i];
	for(j=i;j<L->length-1;j++)
		L->data[j]=L->data[j+1];
	L->length--;
	return 1;
}
int main(){
	SqList *L;
	char a[5]={0};
	ElemType e;

	printf("顺序表的基本运算如下:\n");
	printf("(1)初始化顺序表L\n");
	InitList(L);
	CreateList(L,a,5);
	printf("(2)依次插入a,b,c,d,e元素\n");
	ListInsert(L,1,'a');
	ListInsert(L,2,'b');
	ListInsert(L,3,'c');
	ListInsert(L,4,'d');
	ListInsert(L,5,'e');
	printf("(3)输出顺序表L:");DispList(L);
	printf("(4)输出顺序表L的长度%d\n",ListLength(L));
	printf("(5)判断顺序表L为%s\n",ListEmpty(L)?"空":"非空");
	GetElem(L,3,e);
	printf("(6)输出顺序表L的第3个元素%c\n",e);
	printf("(7)输出元素a的位置为%d\n",LocateElem(L,'a'));
	printf("(8)在第4个元素位置上插入f元素\n"); 
	ListInsert(L,4,'f');
	printf("(9)输出顺序表L:");DispList(L);
	printf("(10)删除顺序表L的第3个元素\n");
	ListDelete(L,3,e);
	printf("(11)输出顺序表L:");DispList(L);
	printf("(12)释放顺序表L\n"); DestroyList(L);
	return 0;
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

202044961

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值