因此,我致力于创建一个名为“创建”的函数,该函数要求用户为链接列表输入数字。如果用户键入“ Y”,则要求输入其他元素,如果用户键入“ N”,则停止并显示链接列表,但是我有点麻烦。当我运行它时,它没有给我输入Y或N的选项,并且当我输入N时,它也会向链接列表添加0。怎么了?
#include <stdio.h>
#include <stdlib.h>
//-------------------------------------------------
struct node {
int data;
struct node *next;
}*start=NULL;
//------------------------------------------------------------
void create() {
char ch;
do {
struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));
printf("Enter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
if(start==NULL) {
start=new_node;
current=new_node;
} else {
current->next=new_node;
current=new_node;
}
printf("Do you want to create another?(Y\N) ");
ch = getchar();
} while(ch!='N');
}
//------------------------------------------------------------------
void display() {
struct node *new_node;
printf("The Linked List : ");
new_node=start;
while(new_node!=NULL) {
printf("%d--->",new_node->data);
new_node=new_node->next;
}
printf("NULL\n");
}
//----------------------------------------------------
int main() {
create();
display();
}
最佳答案
1-将struct node *new_node, *current;
的声明移到do
循环之外(在do之前),因为您希望它们在迭代之间保持其值。
2-在读取数字的scanf之后,换行符保留在缓冲区中,因为用户必须在数字后键入return,而scanf并没有使用它。要在获得是/否答案时跳过此换行符,请以这种方式而不是ch = getchar();
来获得是/否答案:
scanf(" %c", &ch); // notice the blank before the %c, important to skip the newline that remained in the buffer
3-尽管不是必需的,但最好避免在问题中使用转义符
\
,请使用“ Y / N”而不是“ Y \ N”在进行这些修改之后,您的代码可以完美地工作。
关于c - 链接列表问题-为什么当用户键入'N放弃添加更多元素时,为什么将0作为元素添加到列表中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40955873/