链表的增删改查

链表的增删改查的简单代码实现

此操作是基于动态创建链表的基础上。

#include<stdio.h>
#include <stdlib.h>
struct test
{
	int data;
	struct test *next;
};
void printfLink(struct test *head)
{
	struct test *p=head;
	while(p!=NULL)
	{
		
		
			printf("%d",p->data);
		
		p=p->next;
	}
	putchar('\n');
}
struct test *createLink(struct test *head)
{
	struct test *new=NULL;
	
	while(1)
	{
		new=(struct test *)malloc(sizeof(struct test));
		printf("请输入链表数据:");
		scanf("%d",&new->data);
		if(new->data==0)
		{
			printf("退出链表创建\n");
			return head;
		}
		if(head==NULL)
		{
			head=new;
		}
		else
		{
			struct test *p=head;
			while(p->next!=NULL)
			{
				p=p->next;
			}
			p->next=new;
		}
	}
	return head;

}
struct test *zeng(struct test *head,int data,struct test *zeng)//给链表增加一个数据
{
	struct test *p=head;
	while(p!=NULL)
	{
		if(p->data==data)
		{
			
			zeng->next=p->next;
			p->next=zeng;
			return head;
		}
		p=p->next;
	}	
}
struct test *shan(struct test *head,int data)//删除链表中的一个数据
{
	struct test *p=head;
	if(head->data==data)
	{
		return head->next;
	}
	while(p->next!=NULL)
	{
		if(p->next->data==data)
		{
			p->next=p->next->next;
			
			return head;
		}
		p=p->next;
	}	
}
struct test *gai(struct test *head,int data,int cmd)//改变链表中的数据
{
	struct test *p=head;
	while(p!=NULL)
	{
		if(p->data==data)
		{
			p->data=cmd;
			return head;
		}
		p=p->next;
	}
}
struct test *cha(struct test *head,int data)//查找链表中的数据
{
	struct test *p=head;
	while(p!=NULL)
	{
		if(p->data==data)
		{
			printf("找到了\n");
			return head;
		}
		p=p->next;
	}
	
}
int main()
{
	struct test *zen=(struct test *)malloc(128);
	zen->data=6;
	struct test *head=NULL;

	head=createLink(head);
	printfLink(head);
	head=zeng(head,3,zen);//在3的后面加一个6,前提是我们在动态创建链表的时候输入了3
	head=shan(head,4);//删除data=4这个节点,前提是我们在动态创建链表的时候输入了4
	head=gai(head,3,5);//把链表中的3改成5
	head=cha(head,1);//查找链表中是否有1这个数据
	printfLink(head);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值