我已经找到了答案,但每次我最终都没有修复我的代码。 我有一个结构:
struct node {
int x;
struct node * next;
};
我没有任何头/尾。 我想显示每个" x"我的清单。 假设我已经设法从用户输入中创建一个列表。 这是我的代码(不工作):
void printlist(struct node * l)
{
struct node *tmp = l;
while (tmp)
{
printf("%d\n", tmp->x);
tmp = tmp->next;
}
}
我的节目没有显示任何内容;返回0并存在。
编辑:回答你的意见:
typedef struct node * Node;
void add_top(Node l, int x)
{
Node newHead = malloc(sizeof(Node));
newHead->x = x;
newHead->next = l;
l = newHead;
}
void add_bot(Node l, int x)
{
Node tmp = malloc(sizeof(Node));
tmp = l;
while (tmp)
tmp = tmp->next;
Node newTail = malloc(sizeof(Node));
newTail->x = x;
newTail->next = NULL;
tmp = newTail;
}
而在main()中:
int x, keep = 1;
Node l = malloc(sizeof(Node));
l = NULL;
while (keep && scanf("%d", &x))
if (x == 0)
keep = 0;
else if (x % 2 == 0 && x > 0)
add_top(l, x);
else if (x % 2 == 1 && x > 0)
add_bot(l, x);
答案 0 :(得分:1)
函数printlist
是正确的。至于您的问题,则表示l
等于NULL
。
您应该分析将新节点添加到列表中的代码。
这里有很多关于链表的问题。因此,您可以看到单个链接的kist的许多实现。例如,今天我已经回答了similar question
编辑:在您显示列表中的其他代码之后,我可以指出函数add_top
已经错了。它应该看起来像
typedef struct node * Node;
void add_top( Node *l, int x )
{
Node newHead = malloc( sizeof( struct node ) );
newHead->x = x;
newHead->next = *l;
*l = newHead;
}
同样,函数add_bot
是错误的。尝试自己更新。
主要是你必须替换这些陈述
Node l = malloc(sizeof(Node));
l = NULL;
的
Node l = NULL;
否则你会有无意义的内存泄漏。
while循环中的条件错误。
而不是
while (keep && scanf("%d", &x))
应该有
while (keep && scanf("%d", &x) == 1 )