【问题标题】:printing a linked list in c在c中打印一个链表
【发布时间】:2013-01-09 17:42:10
【问题描述】:

我必须为家庭作业制作 2 个链表,将用户给出的整数放在第一个,然后将第一个到第二个列表的每个整数的结果 = x^3。在下面的代码中,我试图打印我放在第一个列表中的内容,并使用 scanf 读取。我还不明白为什么我不能用这种方式打印。你能解释一下吗?提前致谢!!问题是我只打印最后一个元素和 0...:s

代码:

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

struct L1 
{
    int x;
    struct L1 *next1;
};

struct L2 
{
    int x,i,v;
    struct L2 *next2;
};

int main()
{
    int i,N;
    struct L1 *root1; 
    struct L2 *root2;
    struct L1 *conductor1;  
    struct L2 *conductor2;

    root1 = malloc(sizeof(struct L1));  
    root2 = malloc(sizeof(struct L2));
    root1->next1=0;
    conductor1 = root1;
    printf("Dwste arithmo N");
    scanf("%d",&N);
    printf("\nDwse arithmo");
    scanf("%d",&conductor1->x);
    printf("%d",conductor1->x);

    for(i=0; i<N; i++)
    {
        conductor1->next1 = malloc(sizeof(struct L1));
        printf("\nDwste arithmo");
        scanf("%d",&conductor1->x);
        conductor1->next1=0;
    }
    conductor1 = root1;
    while (conductor1 != NULL)
    {
        printf("\n%d",conductor1->x);
        conductor1=conductor1->next1;
    }

    return 0;
}

【问题讨论】:

  • 您到底遇到了什么问题?不会编译,崩溃,报错?
  • 是的,我编辑了 xD 对不起..

标签: c list struct


【解决方案1】:

for 循环中,您永远不会更改conductor1 的值。因此它将始终指向头节点,并且您将始终覆盖该节点的字段。每次迭代分配新节点后需要添加conductor1=conductor1-&gt;next1;才能前进到下一个节点。

【讨论】:

  • 按你的意思改?导体1=导体1->下一个1;
  • @alex777:是的,在malloc之后。
猜你喜欢
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
相关资源
最近更新 更多