【问题标题】:Can't create a list of structs无法创建结构列表
【发布时间】:2015-02-15 02:09:58
【问题描述】:
 #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 --&gt; 1 --&gt; 1---&gt; until NULL。可能出了点问题。提前致谢!

【问题讨论】:

  • 不要在 C 中强制转换 malloc,并尝试在调试器中单步执行代码。它是开发人员用来追踪问题的主要工具之一。

标签: c list pointers struct singly-linked-list


【解决方案1】:

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

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循环。该列表从头到尾添加,从头 = NULL 开始。 root 创建一个单独的结构,head 成为 root 的先前值,然后将其附加到新的 root 值。

输出:

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

【讨论】:

  • 列表的开头是根目录。在 while 循环之后,我使 root = head,root 现在代表整个列表。
【解决方案2】:

这段代码:

head->next=head;
head->next=NULL;

显然没有做你想做的事。它将head 的下一个设置为head 本身,然后将其设置回NULL。如此有效,在每次迭代中,您都在创建一个新结构并将其设置为 next 为 NULL,并且前一个节点会丢失。不要只使用单个 head 变量,而是引入一个您将分配的新变量,将其分配给 head-&gt;next,然后将 head 切换为下一个节点。

【讨论】:

  • 也许head=head-&gt;next; head-&gt;next=NULL; 是正确的?
  • 你为什么不试试呢? ;)
【解决方案3】:

试试下面的

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

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

typedef struct data d_t;

int main( void )
{
    d_t *head = NULL;
    d_t **current = &head;
    int x;

    while ( scanf( "%d" , &x ) == 1 && x == 1 )
    {
        *current = malloc( sizeof( d_t ) );
        ( *current )->x = x;
        ( *current )->next = NULL;
        current = &( *current )->next;
    }       

    /* Prints Whole list */
    for ( current = &head; *current != NULL; *current = ( *current )->next )
    {
        printf( "%d --> " , ( *current )->x );
    }

    return 0;
}

如果以输入为例

1 1 1 1 1 2

然后输出将是

1 --> 1 --> 1 --> 1 --> 1 --> 

我使用您的方法将一个新节点添加到列表的尾部,但如果您将每个新节点添加到列表的头部,代码看起来会更简单。

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 2020-04-20
    • 2020-12-10
    • 2017-02-20
    相关资源
    最近更新 更多