链表的增删改查的简单代码实现
此操作是基于动态创建链表的基础上。
#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;
}