【发布时间】:2021-04-07 16:10:28
【问题描述】:
我正在尝试编写一个程序来创建一个链接列表,当用户输入一个数字时更新该链接列表,并在用户希望终止列表时打印输入的数字。
该程序似乎返回随机数。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cs50.h>
int main(void)
{
typedef struct node
{
int number;
struct node *next;
}
node;
int i = 0;
int x;
char v;
node *list = NULL;
node* temp = NULL;
x = get_int("Enter number: \n");
list = malloc(sizeof(node));
list -> number = x;
list -> next = NULL;
while(i == 0)
{
x = get_int("Enter number: \n");
node *n = malloc(sizeof(node));
temp = malloc(sizeof(node));
n -> number = x;
n -> next = NULL;
for(temp = list; temp->next != NULL; temp = temp -> next)
{
i = 0;
}
temp->next = n;
free(n);
list = temp;
v = get_char("Proceed? :\n");
if(v == 'n')
{
break;
}
else if(v == 'y')
{
continue;
}
else return 1;
}
for(node *temp1 = list; temp1 != NULL; temp1 = temp1 -> next)
{
printf("%d\n",temp1 -> number);
}
}
cs50 头文件允许使用get_ 函数,而不是使用printf 和scanf 的组合。
我想知道这里出了什么问题。
【问题讨论】:
-
temp = malloc(sizeof(node));会导致内存泄漏,不需要 -
仅供参考,您似乎想要在构建链接列表时执行所谓的 前向链接,从而保留原始顺序(而不是将其构建为 LIFO结构,例如堆栈)。它并不像你想象的那么复杂。 see here.
标签: c list data-structures linked-list cs50