我正在使用链表。我想创建一个允许用户将节点添加到列表的循环。我的输出总是有两个额外的空白节点。我相信这与我使用输入函数来获取输入和取消循环的方式有关,但我无法确定问题出在哪里。
我尝试了多种变体,包括以循环表达式终止和 while(1) 在循环内终止。
我希望我在 Windows 10 上使用 Ubuntu 并不重要,但谁知道呢。
#include <stdio.h>
#include <stdlib.h>
#include <stdio_ext.h>
#include <stdbool.h>
typedef struct node {
int val;
struct node * next;
} node_t;
node_t * init_node();
void print_list(node_t * head);
int main(){
node_t * new = init_node();
node_t * head = new;
int c;
printf("\n\tAt any time Press 'N' to quit.\n");
do{
if(c == 'n' || c =='N') {
break;
}
//__fpurge(stdin);
printf("\n\tEnter a value for the new node: ");
scanf("\n%d", &new -> val);
new -> next = init_node();
new = new -> next;
} while(c = getc(stdin) != 'N' && c != 'n');
printf("\n\t");
print_list(head);
return 0;
}
node_t * init_node(){
node_t * temp = (node_t *) malloc( sizeof(node_t *) );
temp -> next = NULL;
return temp;
}
void print_list(node_t * head){
node_t * current = head;
printf("\n\t");
while(current != NULL){
printf("%d->",current -> val);
current = current -> next;
}
printf("null\n");
}
带输入:1、2、3 ...
所需的输出是:
> 1->2->3->null
当前输出为:
>1->2->3->0->0->null
提前致谢!