/*任意输入5个数据测试*/
#include<stdio.h>#include<malloc.h>
struct node
{
int date;
struct node *next;
};
/*插入函数*/
void Insert(struct node *head,int a,int b)
{
struct node *q,*p;
q=head->next;
while(q!=NULL)
{
if(q->date==a)
{
p=(struct node*)malloc(sizeof(struct node));
p->date=b;
p->next=q->next;
q->next=p;
break;
}
q=q->next;
}
}
/*删除函数*/
void Delete(struct node *head,int a)
{
struct node *q,*temp;
q=head->next->next;
temp=head->next;
if(temp->date==a)
{
head->next=q;
return ;
}
while(q!=NULL)
{
if(q->date==a)
{
temp->next=q->next;
break;
}
q=q->next;
temp=temp->next;
}
}
/*取数函数*/
int Get(struct node *head,int x)
{
int i=1;
struct node *q;
q=head->next;
while(q!=NULL)
{
if(i==x)
return q->date;
q=q->next;
i++;
}
printf("不存在这个数!\n");
return 0;
}
/*逆置函数*/
void Reverse(struct node *head)
{
struct node *q,*temp;
q=head->next;
head->next=NULL;
while(q)
{
temp=q->next; //暂存下一结点
q->next=head->next; //把当前节点插入到head节点后面
head->next=q;
q=temp; //移动至下一节点
}
}
/*输出函数*/
void Print(struct node *head)
{
struct node *q;
q=head->next;
while(q!=NULL)
{
printf("%d ",q->date);
q=q->next;
}
printf("\n");
}
int main()
{
int i,x,y,t,m;
struct node *head,*p,*q,*temp;
q=head=(struct node*)malloc(sizeof(struct node));
// head->next=NULL; //前面插入
printf("请输入要测试的数据:\n");
for(i=0;i<5;i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->date);
// p->next=q->next; //在前面插入
// q->next=p;
p->next=NULL; //后面
q->next=p; // 在后面插入
q=p;
}
printf("输入的一系列数据为:");
Print(head);
printf("\n请输入要插入的数的前一位以及要插入的数:");
scanf("%d%d",&x,&y);
Insert(head,x,y);
printf("这组数据变为:");
Print(head);
printf("\n请输入要查找的编号:");
scanf("%d",&t);
if(Get(head,t))
printf("找到这个数为:%d\n",Get(head,t));
printf("请输入要删除的数:");
scanf("%d",&m);
Delete(head,m);
printf("这组数据变为:");
Print(head);
printf("\n单链表逆置为:\n");
Reverse(head);
Print(head);
printf("\n");
return 0;
}