mooc浙大数据结构网课笔记

第二讲(1)

线性表顺序结构

const int MaxSize = 100;

struct LNode
{
	int Data[MaxSize];
	int Last;
};

//初始化
LNode* MakeEmpty()
{
	LNode* L = new LNode;
	L->Last = -1;//表为空时
}

//查找
int Find(LNode L, int elem)
{
	bool tag{ false };
	for (int i{ 0 }; i < L.Last + 1; i++)
	{
		if (elem == L.Data[i])
		{
			tag = true;
			return i;
		}
	}
	if (tag == false) return -1;
}

//插入
LNode* Insert(LNode* L, int pos, int elem)
{
	int len = L->Last + 1;
	if (len > 100) return nullptr;
	for (int i{ len }; i > pos - 1; i--)
	{
		L->Data[i] = L->Data[i - 1];
	}
	L->Data[pos - 1] = elem;
	return L;
}

//删除
LNode* Delete(LNode* L, int pos)
{
	int len = L->Last + 1;
	if (pos > len) return nullptr;
	for (int i{ pos - 1 }; i < len-1; i++)
	{
		L->Data[i] = L->Data[i + 1];
	}
	return L;
}

线性表链式结构

//查找
 LpNode* Find(LpNode* L,int find_elem)//找到应当返回节点
{
	if (L == nullptr) return 0;
	while (L&&L->elem!=find_elem)
	{
		L = L->next;
	}
	if (L) return L;
	else   return nullptr;
}

 //插入
 bool Insert(LpNode* L,int pos,int elem)
 {
	 if (L == nullptr) return false;
	 int pre = pos - 1;//找前一个节点
	 for (int i{ 0 }; (i < pre)&&L; i++)
	 {
		 L = L->next;
	 }
	 if (L)
	 {
		 LpNode* newL = new LpNode{elem,nullptr};
		 newL->next = L->next;
		 L->next = newL;
	 }
	 else
	 {
		 LpNode* newL = new LpNode{ elem,nullptr };
		 newL->next = L;	 }
	 return true;
 }

 //删除
 bool Delete(LpNode* L,int pos)
 {
	 int pre = pos - 1;//找前一个节点
	 for (int i{ 0 }; (i < pre)&&L; i++)
	 {
		 L = L->next;
	 }
	 if (L)
	 {
		 L->next = L->next->next;
		 delete L->next;
		 return true;
	 }
	 else
	 {
		 return false;
	 }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值