[求助]新手的链表问题?????
这是插入函数,当插入第一个数时可以正常输出,插入第二个时就不行了,现象是无限第二个数???请问应该怎么改???? 下面的是全部程序. /*琏表的综合操作*/
#include<stdio.h>
#include<stdlib.h>
struct student
{
int num;
struct student *next;
};
struct student *creat() /*创建琏表的函数*/
{
struct student *head,*p1,*p2;
p1=(struct student*)malloc(sizeof(struct student));
scanf("%d",&(p1->num));
head=p1;
while(p1->num!=0)
{
p2=(struct student*)malloc(sizeof(struct student));
p1->next=p2;
scanf("%d",&(p2->num));
p1=p2;
}
p1->next=NULL;
return(head);
}
void print(struct student *head) /*对琏表进行输出的函数*/
{
struct student *p;
p=head;
if(p==NULL)
printf("no link");
else
while(p->num!=0)
{
printf("%5d",p->num);
printf("\n");
p=p->next;
}
}
mydelete(struct student *head) /*删除琏表中某一结点的函数*/
{
struct student *p,*p1,*p2;
int n;
printf("which element you will delete\n");
scanf("%d",&n);
p=head;p1=head->next;p2=p1->next;
while(p2!=NULL);
{
p=p->next;
p1=p1->next;
p2=p2->next;
if(p1->num==n);
{
p2=p->next;
free(p1);
return 1;
}
}
return 0;
}
insert(struct student *head) /*对琏表的末尾插入一个元素*/
{
struct student *p2,*p,*p1,*p3;
int n;
p2=head->next,p=head,p1=head->next,p3=head;
printf("input the element\n");
scanf("%d",&n);
while(p!=NULL)
{
if(p->num==n) /*判断琏表中是否有与要插入的元素相同的结点*/
return 0;
p=p->next;
}
while(p1->num!=NULL)
{
p1=p1->next;p3=p3->next;
}
p2=(struct student*)malloc(sizeof(struct student));
p2=p3->next;
p2->num=n; /*当没有相同元素时,在末尾插入元素*/
p2->next=NULL;
return 1;
}
main()
{
struct student * head;
int h,k;
char choose;
k=10;
printf("C--creat link,D--delete element,I--insert link,P--print link,O--out\n");
for(k=0;k<=10;k++)
{
printf("choose...\n");
scanf("%c",&choose);
switch(choose) /*选择对琏表的操作*/
{
case'c': /*创建并打印琏表*/
{
printf("enter element\n");
head=creat();
printf("the link is\n");
print(head);
}
break;
case 'd':
{
h=mydelete(head);
if(h==1)
{
printf("the new link\n");
print(head);
}
if(h==0)
printf("Not Found The Element");
}
break;
case 'i':
{
h=insert(head);
if(h==1)
{
printf("new link is\n");
print(head);
}
if(h==0)
printf("link have had the element\n");
}
break;
case 'p':
print(head);
break;
default:
printf("error again\n");
}
if(choose=='o')
break;
}
getch();
}