首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用c++打印链表

用c++打印链表
EN

Stack Overflow用户
提问于 2013-01-10 01:42:10
回答 1查看 144关注 0票数 1

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

代码:

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-10 01:47:35

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14243215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档