无法创建结构列表

标签 c list pointers struct singly-linked-list

 #include <stdio.h>
 #include <stdlib.h>

struct data {
    int x;
    struct data *next;
};

typedef struct data d_t;


/*  Main fuction  */
int main(){

    int x;
    d_t  test , *root , *head;
    scanf("%d" , &x);

    /*   Sets pointer values */
    root=&test;
    head=root;
    head->next=NULL;

    /*   While fuction represends "ADD struct to list"  */
     while(x==1){


    /* Allocating memory for new struct */
    head=(d_t*)malloc(sizeof(d_t));
    head->x=1;
    printf("%d\n" , head->x);

    /* Sets pointer values for next struct  */
    head->next=head;
    head->next=NULL;

   /* Scanfs 'x' to see if user wants to continue */
   scanf("%d" , &x);
}

    /* Prints Whole list */
    while(root!=NULL){
    printf("%d --> " , root->x);
    root=root->next;    
    }

     return 0;
 }

程序应打印:1 --> 1 --> 1---> 直到 NULL。可能出了什么问题。提前致谢!

最佳答案

以下是构建链表的常规方法:

int main() {
  int x;
  d_t *root, *head; // you don't need "test"
  scanf("%d", &x);
  head = NULL;
  while (x == 1) {
    root = (d_t*)malloc(sizeof(d_t));
    root->x = 1;
    root->next = head;
    head = root;
    scanf("%d", &x);
  }
  root = head;
  while (root) {
    printf("%d\n", root->x);
    root = root-> next;
  }
}

分析第一个 while 循环。该列表从尾部到头部添加,从 head = NULL 开始。 root 创建单个结构体,head 成为 root 之前的值,然后将其附加到新的 root 值。

输出:

1->1->1->..etc...-> NULL

关于无法创建结构列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27510155/

相关文章:

c# - 查找列表中最常出现的项目的方法

C++避免检查双指针持有的未初始化值

c++ - 在 C++ 中使用 BLAS 对来自不同数组的值进行点积

c - 为什么下面的 printf 会导致段错误?

c - MIPS 上的 Valgrind 报告没有堆使用

c - obj-y += something/in linux kernel Makefile 是什么意思?

c - if (a/b == value1 or value2) 我如何用 C 语言编写这个?

c++ - 音频输出C语言(新手)

python re.sub 带有要查找的单词列表

我的类中的 C++ 运行时错误