[英]printing a linked list in c
I have to make for homework 2 linked lists, put integers given from the user in the first and then put the result=x^3 for each integer of the first to the second list. 我必须为homework 2链表制作,在第一个中输入用户给出的整数,然后将结果= x ^ 3放在第一个到第二个列表的每个整数中。 In the following code, I am trying to print what I put in the first list, reading with scanf.
在下面的代码中,我试图打印我放在第一个列表中的内容,用scanf读取。 I haven't yet understood why can't I print by this way.
我还不明白为什么我不能用这种方式打印。 Could you please explain?
你能解释一下吗? Thanks in advance!!
提前致谢!! The problem is that I print only the last element and 0... :s
问题是我只打印最后一个元素和0 ...:s
Code: 码:
#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;
}
In the for
loop you are never changing the value of conductor1
. 在
for
循环中,您永远不会更改conductor1
的值。 So it will always point to the head node, and you will always overwrite the fields of that node. 因此它始终指向头节点,您将始终覆盖该节点的字段。 You need to add
conductor1=conductor1->next1;
你需要添加
conductor1=conductor1->next1;
after allocating the new node to advance to the next node in each iteration. 在分配新节点以在每次迭代中前进到下一个节点之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.