C语言 为什么我的循环会创建额外的链表节点?



我正在使用linkedlist。我想创建一个循环,允许用户将节点添加到列表中。我的输出总是有两个额外的空白节点。我相信这与我使用输入函数来获取输入和取消循环的方式有关,但我无法确定问题所在。

我尝试了各种变体,包括终止为循环表达式和 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("ntAt any time Press 'N' to quit.n");
do{
if(c == 'n' || c =='N') {
break;
}
//__fpurge(stdin);
printf("ntEnter 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("nt");
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("nt");
while(current != NULL){
printf("%d->",current -> val);
current = current -> next;
}
printf("nulln");
}

带输入: 1, 2, 3 ...

所需的输出为:
>1->2->3->空

当前输出为:
>1->2->3->0->0->空

提前感谢!

每个循环,你都这样做:

  • new->val = user_input
  • new->next = new_node()
  • new = new->next

因此,每次在列表末尾添加一个新的未初始化节点。这恰好在您当前的系统中0,但不一定如此。

最初,您的列表包含:

[?] -> null

? 表示未初始化的数据,恰好为0,[] 表示new指向的节点。

在第一次循环中输入1时,您可以:

  • 将 ? 更改为 1
  • 使用未初始化的数据创建新的next节点
  • 指出new

因此,您的列表包含

1 -> [?] -> null

然后输入 2 并得到:

1 -> 2 -> [?] -> null

最后,print_list将执行以下操作:

[1] -> 2 -> ? -> null
Prints `1 ->`
1 -> [2] -> ? -> null
Prints `2 ->`
1 -> 2 -> [?] -> null
Prints `0 ->` // But could print anything.
1 -> 2 -> ? -> [null]
Breaks the loop and prints `null`

此外,您的malloc正在为node_t *请求空间,这是指向数据结构的指针;您应该调用malloc(sizeof(node_t))malloc(sizeof(*temp))。您可能无意中覆盖了某些内容。

我假设第二个零来自你使用程序的方式:如果你按下:1enterenter2enterenter3enterenter、[无]、entern,那么scanf将收到一个空字符串,计算0

您应该检查scanf的返回值:它报告成功匹配的字段数。

处理用户输入的更好方法可能是:

while (1) {
char user_input[BUFSIZE];
fgets(user_input, BUFSIZE, stdin);
if (sscanf(user_input, "%d", node->val)) {
...
} else if (user_input[0] == 'n' || user_input[0] == 'N') {
break;
}
}

最新更新