c语言链表的插入 查询 删除

c语言实验十五链表
链表的插入 查询 删除,
不会吧,来看看月腾兄的;

#include<stdio.h>
#include<stdlib.h>
struct node
{
	int data;
	struct node *next;
};
//向链表指定位置插入数据
int insert(struct node *L, int i, int *e)
{
	struct node *p, *s;
	p = L;
	int j = 0;
	while (p&&j<i-1)
	{
		p = p->next;
		++j;
	}
	if (!p || j > i - 1)return 0;
	s= (struct node*)malloc(sizeof(struct node));
	s->data = *e;
	s->next = p->next;
	p->next = s;
	return 1;
}
//创建链表
void Create(struct node *L, int n)
{
	int i;
	int v;
	struct node *p;
	L->next = NULL;

	//循环录入数据
	for (i = n; i > 0; --i)
	{
		p = (struct node *) malloc(sizeof(struct node));
		scanf_s("%d", &v);
		p->data = v;
		p->next = L->next;  //头插法
		L->next = p;
	}
}
//输出链表中的数据
int Print(struct node *L, char* s) {
	struct node *p;
	printf("%s", s);
	p = L->next;
	if (p == NULL)
	{
		printf("链表为空\n");
		return 0;
	}
	while (p != NULL) {
		printf("%d   ", p->data);
		p = p->next;
	}
	printf("\n");
	return 1;
}
//删除链表中指定位置的数据
int Delete(struct node *L, int i, int *e)
{
	struct node *p, *q;
	p = L;
	int j = 0;
	while (p->next && j < i - 1)
	{
		p = p->next;
		++j;
	}
	if (!(p->next) || j > i - 1) return 0;
	q = p->next;
	p->next = q->next;
	*e = q->data;
	free(q);
	return 1;
}
//获取链表中指定位置的数据
int find(struct node *L, int i, int *e)
{
	//L为带头结点的单链表的头指针。当第i个元素存在时,其赋值给e并返回1,否则返回0
	struct node *p;
	p = L->next;
	int j = 1;
	while (p&&j < i)
	{
		p = p->next;
		++j;
	}
	if (!p || j > i) return 0;
	*e = p->data;
	return 1;
}

 void main()
 {
	 struct node L;
	 printf("请输入3个初始数据");
	 Create(&L, 3);
	 Print(&L,"初始化的链表");
	//定义inser函数的参数,插入位置和数值
	 //插入功能演示
	 int s, v;
	 printf("请输入数据插入的位置s 和数值v :");
	 scanf_s("%d%d", &s, &v);
	 printf("%s", insert(&L, s, &v) ? "插入成功.\n" : "插入失败.\n");
	 Print(&L, "插入后的链表:");
	 //删除功能演示
	 printf("请输入数据删除的位置s :");
	 scanf_s("%d", &s);
	 if (Delete(&L, s, &v))
		 printf("删除成功.删除的数据是:%d\n", v);
	 else
		 printf("删除失败.位置有误.");
	 Print(&L, "删除后的链表:");
	 //查询功能演示
	 printf("请输入要查询的数据位置s :");
	 scanf_s("%d", &s);
	 find(&L, s, &v);
	 printf("第%d个数是:%d\n\n", s, v);
	 system("pause");
	 return 0;
 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值