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



我是一名初学者,我正致力于通过用户输入创建和打印链接列表。创建部件进行得很顺利,但每次我尝试打印最终列表时,都会收到令人讨厌的"list IS EMPTY"消息。*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 locatedn");
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("nn");
return 0;
}

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

createnodelist函数不执行任何操作(除了泄漏内存(。

它声明了一个名为stnode:的局部变量

struct node *stnode = (struct node*)malloc(sizeof(struct node)), *fnnode, *temp;

但是当函数返回时,该局部变量会被销毁,因此无法访问您构建的列表。

特别地,这个stnode与同名的全局变量无关。

您的printnode函数执行以下操作:

struct node *n = (struct node*)malloc(sizeof(struct node));
n = stnode;

(请注意,这是内存泄漏:n = stnode覆盖了从malloc返回的指针,该指针现在变得不可访问且无法释放。(

这个stnode是一个全局变量。它从未被设置,因此它仍然包含其初始值NULL

createnodelist中,写入

void createnodelist(int n)
{
int num, i;
stnode = (struct node*)malloc(sizeof(struct node));
struct node *fnnode, *temp;

而不是

void createnodelist(int n) {
int num, i;
struct node *stnode = (struct node*)malloc(sizeof(struct node)), *fnnode, *temp;

否则,您将引入一个局部变量,该变量将隐藏稍后在printnode函数中使用的全局stnode

BTW:printnode中的struct node *n = (struct node*)malloc(sizeof(struct node));非常糟糕,因为您在下一条语句中覆盖了n的值;写struct node *n = stnode就足够了。

最新更新