数据结构顺序表实验2.1实验题1

#include<iostream>
using namespace std;
#define MaxSize 50
typedef struct {
	char data[MaxSize];
	int length;
}SqList;
void InitList(SqList *&L)
{
	L = (SqList*)malloc(sizeof(SqList));
	L->length = 0;
}
void DestroyList(SqList *L)
{
	free(L);
}
int ListEmpty(SqList*L)
{
	if (L->length)
	{
		return true;
	}
	return false;
}
int ListLength(SqList*L)
{
	return (L->length);
}
void DispList(SqList*L)
{
	for (int i = 0; i < L->length; i++)
	{
		cout << L->data[i];
	}
	cout << endl;
}
bool GetElem(SqList* L, int i, char& e)
{
	if (i<1||i>L->length)
	{
		return false;
	}
	i--;
	e = L->data[i];
	return true;
}
int LocateElem(SqList* L, char e)
{
	int i = 0;
	while (i<L->length&&L->data[i]!=e)
	{
		i++;
	}
	if (i>=L->length)
	{
		return 0;
	}
	return i + 1;
}
bool ListInsert(SqList*&L,int i,char e)
{
	if (i<1||i>L->length+1||L->length>=MaxSize)
	{
		return false;
	}
	i--;
	for (int 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,char&e)
{
	if (i<1||i>L->length)
	{
		return false;
	}
	i--;
	e = L->data[i];
	for (int j = i; j < L->length-1; j++)
	{
		L->data[j] = L->data[j + 1];
	}
	L->length--;
	return true;
}
int main()
{
	SqList* L;
	InitList(L);
	ListInsert(L, 1, 'a');
	ListInsert(L, 2, 'b');
	ListInsert(L, 3, 'c');
	ListInsert(L, 4, 'd');
	ListInsert(L, 5, 'e');
	DispList(L);
	cout << ListLength(L) << endl;
	cout << (ListEmpty(L) ? "非空" : "空") << endl;
	char e;
	GetElem(L, 3, e);
	cout << e << endl;
	cout << LocateElem(L, 'a') << endl;
	ListInsert(L, 4, 'f');
	DispList(L);
	ListDelete(L, 3, e);
	DispList(L);
	DestroyList(L);
	return 0;
}

首先作者尝试在void InitList(SqList *&L)等需要+&的部分不加,运行结果说是未初始化本地变量,分析之后发现,我们在主函数中定义了一个指针。

而将一个指针传入是麻烦的,这里用了c++的引用语法,方便了许多,作者搞混了,比如下图例子。定义整型变量a,传入他的地址,用&,形参用int 8b,没有问题,但是第一张图是定义一个指针L。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值