C 链表
#include<stdio.h>
#include<stdlib.h>
typedef struct link
{
int data;
struct link *next;
}A;
//创建链表
A *creat()
{
A *head=NULL,*p,*pr;
p=(A *)malloc(sizeof(A));
scanf("%d",&p->data);
while(p->data!=0)
{
if(head==NULL)
{
head=p;
}
else
{
pr->next=p;
}
pr=p;
p=(A *)malloc(sizeof(A));
scanf("%d",&p->data);
}
pr->next=NULL;
return head;
}
//插入链表
A *insert(A *head,int num,A *node)
{
A *p=head;
while(p->data!=num&&p->next!=NULL)
{
p=p->next;
}
if(num==p->data)
{
node->next=p->next;
p->next=node;
}
else
{
printf("123!!!\n");
}
return head;
}
void print(A *head)
{
A *p;
p=head;
if(p==NULL)
printf("List is null!\n");
else
{
do
{
printf("%d \n",p->data);
p=p->next;
}while(p!=NULL);
}
}
//销毁链表
void des(A *head)
{
A *p=head,*p1=NULL;
while(p!=NULL)
{
p1=p;
p=p->next;
free(p1);
}
}
//链表删除
A *del(A *head,int num)
{
A *p1,*p2;
p1=head;
while(p1->data!=num&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(num==p1->data)
{
p2->next=p1->next;
free(p1);
p1=NULL;
printf("\ndelete %d success!\n",num);
}
else
{
printf("\n%d not been found!\n",num);
}
return head;
}
int main()
{
A *p,*p1;
int n;
p=creat();
print(p);
printf("\nPlease input insert index:");
scanf("%d",&n);
p1=(A *)malloc(sizeof(A));
printf("\nPlease input insert data:");
scanf("%d",&p1->data);
p=insert(p,n,p1);
print(p);
printf("\nPlease input delete index:");
scanf("%d",&n);
p=del(p,n);
print(p);
des(p);
return 0;
}