C语言实现单链表(不带头节点)的删除插入完整代码

 注意:不带头节点的单链表删除插入操作第一个节点的时候都要特殊讨论

以下代码是用C语言实现的完整代码可上机运行


#include<stdio.h>
#include<malloc.h>
struct linknode
{
	int data;
	struct linknode* next;
};
void init(struct linknode** L)
{
	(*L) = NULL;
}
void insect(struct linknode** L, int i, int n)
{
	if (i < 1)
		printf("插入位置错误\n");
	else if (i == 1)
	{
		printf("开始插入\n");
		struct linknode* s = (struct linknode*)malloc(sizeof(struct linknode));
		printf("申请位置成功\n");
		s->data = n;
		s->next = (*L);
		(*L) = s;
		printf("插入成功\n");
	}
	else
	{
		int count = 1;
		struct linknode* p = (*L);
		while (p&&count < i - 1)
		{
			p = p->next;
			count++;
		}
		if (p)
		{
			struct linknode* s = (struct linknode*)malloc(sizeof(struct linknode));
			s->data = n;
			s->next = p->next;
			p->next = s;
			printf("插入成功\n");
		}
		else
			printf("插入失败\n");
	}
}
void delete(struct linknode** L,int i)
{
	if(i<1||(*L)==NULL)
	printf("删除失败");
	else if(i==1)
	{
		(*L)=(*L)->next;
	} 
	else
	{
	 	int count=1;
	 	struct linknode* p=(*L);
	 	while(p&&count<i-1)
	 	{
	 		p=p->next;
	 		count++;
		}
		if(p)
		{
			p->next=p->next->next;
			printf("删除成功\n");
		}
		else
		printf("删除位置不恰当\n");
	}
}
void point(struct linknode* L)
{
	while (L)
	{
		printf("%d,", L->data);
		L = L->next;
	}
}
int main()
{
	struct linknode* L;
	init(&L);
	printf("初始化成功不带头节点单链表\n");
	insect(&L, 1, 11);//在第一个位置插入元素11
	insect(&L, 2, 22);
	insect(&L, 3, 33);
	insect(&L, 3, 44);
	insect(&L, 6, 66); 
	delete(&L,1);//删除第一个元素 
	delete(&L,3);//删除第三个元素 
	delete(&L,5);//删除第五个元素 
	printf("请打印输出链表\n");
	point(L);//打印函数
	return 0;
}

运行结果:

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值