C语言实现单链表的插入

1.带头结点按位插入(指定结点后插)

//带头结点按位序插入
bool ListInsert(LinkList &L, int i, int e) {
	if (i < 1)
		return false;
	LNode *p;//指针p指向扫描到的结点
	int j = 0;//当前p指向的第几个结点
	p = L;//L指向头结点,头结点是第0个结点(不存数据)
	while (p != NULL && j < i - 1) {//循环找到第i-1个结点
		p = p->next;
		j++;
	}
	return InsertNextNode(p, e);
}

//指定结点后插
bool InsertNextNode(LNode *p, int e)
{
	if (p = NULL)
		return false;
	LNode * s = (LNode*)malloc(sizeof(LNode));
	if (s == NULL)
		return false;
	s->data = e;
	s->next = p->next;
	p->next = s;
	return true;
}

2.不带头节点按位插入(指定结点后插)

bool ListInsert_no(LinkList &L, int i, int e) {
	if (i < 1)
		return  false;
	if (i == 1){
		LNode* t = (LNode*)malloc(sizeof(LNode));
		t->data = e;
		t->next = L;
		L = t;//头指针指向新的结点t
		return true;
	}
	LNode *p;
	int j = 1;
	p = L;//p指向第一个结点
	while (p != NULL && j < i - 1) {
		p = p->next;
		j++;
	}
	return InsertNextNode(p, e);
}

//指定结点后插
bool InsertNextNode(LNode *p, int e)
{
	if (p = NULL)
		return false;
	LNode * s = (LNode*)malloc(sizeof(LNode));
	if (s == NULL)
		return false;
	s->data = e;
	s->next = p->next;
	p->next = s;
	return true;
}

3.指定结点前插

//指定结点前插
bool InsertPriorNode(LNode *p, int e) {
	if (p == NULL)
		return false;
	LNode * s = (LNode*)malloc(sizeof(LNode));
	if (s == NULL)
		return false;
	s->next = p->next;
	p->next = s;//新节点连接到s中
	s->data = p->data;//将p中的元素复制到s中
	p->data = e;//p中元素覆盖为e
}


//指定结点前插
bool InsertPriorNode(LNode *p, LNode*s) {
	if (p == NULL||s==NULL)
		return false;
	s->next = p->next;
	p->next = s;
	int temp= p->data;
	p->data = s->data;
	s->data = temp;
	return true;
}

4.指定结点后插

bool InsertNextNode(LNode *p, int e)
{
	if (p = NULL)
		return false;
	LNode * s = (LNode*)malloc(sizeof(LNode));
	if (s == NULL)
		return false;
	s->data = e;
	s->next = p->next;
	p->next = s;
	return true;
}

总结思维导图:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值