以下是增删查改操作
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct Node//创建结构体
{
int data;
struct Node *next;
};
void printfLink(struct Node *head)//传递头结点的地址,打印链表
{
while(head)
{
printf("%d ",head->data);
head=head->next;
}
putchar('\n');
}
int acquireLinkNumber(struct Node *head)//传递头结点的地址,获得链表个数
{
int Number=0;
while(head)
{
Number++;
head=head->next;
}
return Number;
}
void findLinkData(struct Node *head,int data,int result)//传递头结点的地址和查找的数据,查看是否存在此数据 并修改
{
while(head)
{
if(head->data==data)
{
printf("success\n");
head->data=result;
break;
}
head=head->next;
}
if(head==NULL)
printf("fail\n");
}
void insertLinkNodeBehind(struct Node *head,int data,struct Node *new)//后插
{
while(head)
{
if(head->data==data)
{
new->next=head->next;
head->next=new;
printf("success\n");
break;
}
head=head->next;
}
if(head==NULL)
printf("fail\n");
}
struct Node* insertLinkForward(struct Node *head,int data,struct Node *new)//前插可能改变首节点,故返回一个结构体指针
{
struct Node *p=head;
if(data==head->data)
{
new->next=head;
printf("success and firstNode\n");
return new;
}
while(head->next)
{
if(data==head->next->data)
{
new->next=head->next;
head->next=new;
printf("success\n");
return p;
}
head=head->next;
}
printf("fail\n");
return p;
}
struct Node* deleteLinkNode(struct Node* head,int data)//删除节点,可能会删除首节点,故返回节点地址
{
struct Node *p=head;
if(head->data==data)
{
printf("success and firstNode\n");
return head->next;
}
while(head->next)
{
if(head->next->data==data)
{
head->next=head->next->next;
printf("success\n");
return p;
}
head=head->next;
}
printf("fail\n");
return p;
}
struct Node* dynamicHeadInsertLink(struct Node* head)//动态头插 改变首节点,故返回节点地址
{
struct Node* new;
int data;
new=(struct Node*)malloc(sizeof(struct Node));
printf("pelase input your data!\n");
scanf("%d",&(new->data));
if(new->data==0)
return head;
if(head==NULL)
{
new->next=NULL;
return new;
}
else
{
new->next=head;
return new;
}
}
struct Node* createLink()//创建链表
{
struct Node* new;
struct Node* head;
struct Node* temp;
struct Node* temp2;
new=(struct Node*)malloc(sizeof(struct Node));
printf("pelase input your data!\n");
scanf("%d",&(new->data));
head=new;
new->next=NULL;
while(1)
{
temp=(struct Node*)malloc(sizeof(struct Node));
temp2=new;
new->next=temp;
new=temp;
printf("pelase input your data!\n");
scanf("%d",&(temp->data));
if(temp->data==0)
{
temp2->next=NULL;
free(temp);
return head;
}
temp->next=NULL;
}
}
int main()
{
//struct Node *head=NULL;
//struct Node *temp=NULL;
//printf("printfLink\n");
//printfLink(&t1);//打印链表
//printf("acquireLinkNumber\n");
//printf("Number:%d\n",acquireLinkNumber(&t1));//获取链表个数
//findLinkData(&t1,1,5);//查找是否存在此节点并修改
//insertLinkNodeBehind(&t1,4,&new);//后插
//printfLink(insertLinkForward(&t1,4,&new));//前插
//printfLink(deleteLinkNode(&t1,1));//删除节点
//printfLink(dynamicHeadInsertLink(head));//动态头插一个
/*while(1)
{
temp=head;
head=dynamicHeadInsertLink(head);
if(temp==head)
break;
}
printfLink(head);*///动态头插多个 输入0则停止插入
//printfLink(createLink());//创建链表,输入0结束
return 0;
}