你能帮我理解为什么while循环在以下代码中不起作用吗?
#include<stdio.h>
#include<stdlib.h>
typedef struct node_type{
int data;
struct node_type *next;
}node;
typedef node *list;
list head;
void main()
{
list temp,new;
head=NULL;
int n;
char ch;
temp=(list) malloc(sizeof(node));
printf("nGive data: ");
scanf("%d",&temp->data);
head=temp;
printf("n");
printf("Enter Data? (y/n): ");
scanf("%c",&ch);while(getchar()!='n');
while(ch=='y'||ch=='Y')
{
new=(list) malloc(sizeof(node));
printf("Give data: ");
scanf("%d",&new->data);while(getchar()!='n');
temp->next=new;
temp=new;
printf("nEnter more data(y/n): ");
scanf("%c",&ch);while(getchar()!='n');
}
temp->next=NULL;
traverse(head);
}
输出如下:给出数据:2
输入更多数据(年/号(: y
阿拉伯数字
程序到此终止。
在scanf()
之前,您不需要在任何地方都使用while(getchar()!='n');
。这会导致您的计划终止。您可以改用scanf("n%c", &ch);
。另外,建议在new = (list)malloc(sizeof(node));
之后写new->next = NULL;
。 此外,您错过traverse()
功能。
试试这个修改后的代码:-
#include <stdio.h>
#include <stdlib.h>
typedef struct node_type
{
int data;
struct node_type *next;
} node;
typedef node *list;
list head;
void traverse(node *head) // This is simple traverse function just to demonstrate code.
{
while (head != NULL)
{
printf("%d ", head->data);
head = head->next;
}
}
void main()
{
list temp, new;
head = NULL;
int n;
char ch;
temp = (list)malloc(sizeof(node));
temp->next = NULL;
printf("nGive data: ");
scanf("%d", &temp->data);
head = temp;
printf("n");
printf("Enter Data? (y/n): ");
scanf("n%c", &ch);
while (ch == 'y' || ch == 'Y')
{
new = (list)malloc(sizeof(node));
new->next = NULL;
printf("Give data: ");
scanf("%d", &new->data);
new->next = NULL;
temp->next = new;
temp = new;
printf("nEnter more data(y/n): ");
scanf("n%c", &ch);
}
temp->next = NULL;
traverse(head);
}
输出:-
Give data: 2
Enter Data? (y/n): y
Give data: 22
Enter more data(y/n): y
Give data: 32
Enter more data(y/n): n
List is : 2 22 32