gpt4 book ai didi

c - 根据用户输入打印链接列表

转载 作者:行者123 更新时间:2023-11-30 19:29:17 25 4
gpt4 key购买 nike

我是初学者,我正在通过用户输入创建和打印链接列表。创建部分进展顺利,但每次我尝试打印最终列表时,我都会收到恼人的“列表为空”消息。 *stnode 指针可能有问题。有人可以帮我吗?感谢您的每一个回答!

代码

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

struct node
{
int data;
struct node *next;
}*stnode;

//function creating the linked list
void createnodelist(int n)
{
int num, i;
struct node *stnode = (struct node*)malloc(sizeof(struct node)), *fnnode, *temp;

if (stnode==NULL) {
printf("Memory cannot be located");
return;
}

//creating head of the list
else {
printf("Number 1 = ");
scanf("%d", &num);
stnode->data = num;
stnode->next = NULL;
if (stnode == NULL) {
printf("Memory can not be located");
}
temp = stnode;
}

//Creating all others parts of linked list
for (i=2; i<=n; i++)
{
fnnode = (struct node*)malloc(sizeof(struct node));
if (fnnode==NULL) {
printf("Memory cannot be located\n");
break;
}
printf("Number %d = ", i);
scanf("%d", &num);
fnnode->data = num;
fnnode->next = NULL;
temp->next = fnnode;
temp = temp->next;
}
}

//function printing the output
void printnode()
{
struct node *n = (struct node*)malloc(sizeof(struct node));

n = stnode;
if (stnode == NULL) {
printf("LIST IS EMPTY"); //HERE IS MY PROBLEM
}
while (n!=NULL) {
printf("%d ", n->data);
n = n->next;
}
}

int main()
{
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("\n");

createnodelist(n);
printf("\n");

printnode();

printf("\n\n");
return 0;
}

最佳答案

在 createnotelist() 中,您使用 stnode 的本地声明隐藏全局 stnode。因此,全局 stnode 保持未定义或为 null,并且不会在 createnodelist() 中进行修改。

关于c - 根据用户输入打印链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53126443/

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