C 如何在链表中存储字符
我在以下代码中存储字符时遇到问题。 它是编译的,但它不需要第二、第四、第六。。。字符作为输入C 如何在链表中存储字符,c,C,我在以下代码中存储字符时遇到问题。 它是编译的,但它不需要第二、第四、第六。。。字符作为输入 struct ll { char data; struct ll *next; }; 下面是创建链接列表的代码 struct ll* create_ll(struct ll *start){ struct ll *p1,*p2; char a; printf("Enter q to stop\n"); printf("Enter data:");
struct ll {
char data;
struct ll *next;
};
下面是创建链接列表的代码
struct ll* create_ll(struct ll *start){
struct ll *p1,*p2;
char a;
printf("Enter q to stop\n");
printf("Enter data:");
scanf("%c",&a);
while(a != 'q'){
p1 = (struct ll*)malloc(sizeof(struct ll*));
p1 -> data = a;
if(start == NULL){
start = p1;
p2 = p1;
p1 -> next = NULL;
}
else{
p2 -> next = p1;
p1 -> next = NULL;
p2 = p1;
}
printf("Enter data:");
scanf("%c",&a);;
}
return start;
}
改变
scanf("%c",&a);
到
您的scanf正在将enter键读取为\n字符
您可能已经看到了,因为我怀疑程序输出输入数据:每次两次。请更好地缩进代码。另外警告:顺便说一句,您正在malloc'ing指针的大小,而不是实际的结构大小。应为mallocsizeofstruct ll;应该是mallocsizeof*p1并用它完成。
scanf(" %c",&a);
// ^ Space here