gpt4 book ai didi

无法创建结构列表

转载 作者:行者123 更新时间:2023-11-30 20:51:40 25 4
gpt4 key购买 nike

 #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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com