为什么运行结果根本就停不下来?求大神解答 20
#include<stdio.h>#include<stdlib.h>structlink*Append(structlink*head);voidDelete(stru...
#include<stdio.h>
#include<stdlib.h>
struct link *Append(struct link *head);
void Delete(struct link *head);
void Display(struct link *head);
struct link
{
int data;
struct link *next;
};
void main()
{
char c;
int i=0;
struct link *head=NULL;
printf("Do You want to append?");
scanf(" %c",&c);
while(c=='y'||c=='Y')
{
head=Append(head);
Display(head);
printf("Do You Want to append?");
scanf(" %c",&c);
i++;
}
printf("%d nodes have been recorded.",i);
Delete(head);
}
struct link *Append(struct link *head)
{
struct link *pr=NULL,*p=head;
int data;
pr=(struct link *)malloc(sizeof(struct link));
if(pr==NULL)
{
printf("Fail To Creat!\n");
exit(0);
}
if(head==NULL)
{
head=pr;
}
else
{
while(p->next!=NULL)
{
p=p->next;
}
p->next=pr;
}
printf("Please Input node information:");
scanf("%d", &data);
pr->data=data;
pr->next=NULL;
return head;
}
void Display(struct link *head)
{
struct link *p = head;
int j=1;
while(p != NULL)
{
printf("%5d%10d\n",j,p ->data);
j++;
}
}
void Delete(struct link *head)
{
struct link *p=head,*pr=NULL;
while(p!=NULL)
{
pr=p;
p=p->next;
free(pr);
}
} 展开
#include<stdlib.h>
struct link *Append(struct link *head);
void Delete(struct link *head);
void Display(struct link *head);
struct link
{
int data;
struct link *next;
};
void main()
{
char c;
int i=0;
struct link *head=NULL;
printf("Do You want to append?");
scanf(" %c",&c);
while(c=='y'||c=='Y')
{
head=Append(head);
Display(head);
printf("Do You Want to append?");
scanf(" %c",&c);
i++;
}
printf("%d nodes have been recorded.",i);
Delete(head);
}
struct link *Append(struct link *head)
{
struct link *pr=NULL,*p=head;
int data;
pr=(struct link *)malloc(sizeof(struct link));
if(pr==NULL)
{
printf("Fail To Creat!\n");
exit(0);
}
if(head==NULL)
{
head=pr;
}
else
{
while(p->next!=NULL)
{
p=p->next;
}
p->next=pr;
}
printf("Please Input node information:");
scanf("%d", &data);
pr->data=data;
pr->next=NULL;
return head;
}
void Display(struct link *head)
{
struct link *p = head;
int j=1;
while(p != NULL)
{
printf("%5d%10d\n",j,p ->data);
j++;
}
}
void Delete(struct link *head)
{
struct link *p=head,*pr=NULL;
while(p!=NULL)
{
pr=p;
p=p->next;
free(pr);
}
} 展开
1个回答
展开全部
因为你在输出的时候,输出了第一个节点,但指针没有移动,p一直指在第一个节点,死循环了。
while()循环里加一句p = p->next。
void Display(struct link *head)
{
struct link *p = head;
int j=1;
while(p != NULL)
{
printf("%5d%10d\n",j,p ->data);
p = p->next; // 加一句这个
j++;
}
}
然后是循环输入字符的时候,输入区要清除缓存,不然scanf会读取到你之前填写的结点的值,转换成字符后肯定是数字,不会是y,判断c不是y,你就不能再输入了。
while(c=='y'||c=='Y')
{
head=Append(head);
Display(head);
printf("Do You Want to append?");
fflush(stdin); // 加一句这个
scanf(" %c",&c);
i++;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询