我必须做作业2链表,把用户给出的整数放在第一个链表中,然后把第一个整数的result=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;
}发布于 2013-01-10 01:47:35
在for循环中,您永远不会更改conductor1的值。因此,它将始终指向头节点,并且您将始终覆盖该节点的字段。您需要在分配新节点后添加conductor1=conductor1->next1;,以便在每次迭代中前进到下一个节点。
https://stackoverflow.com/questions/14243215
复制相似问题