繁体   English   中英

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

[英]Why is my loop creating extra linked list nodes?

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

我尝试了多种变体,包括终止为循环表达式以及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->空

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

提前致谢!

每个循环,您都可以这样做:

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

因此,每次在列表的末尾添加一个新的未初始化的节点。 在您当前的系统中,该值恰好为0 ,但不必为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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM