簡體   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