[英]printing a linked list in c
我必須為homework 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;
}
在for
循環中,您永遠不會更改conductor1
的值。 因此它始終指向頭節點,您將始終覆蓋該節點的字段。 你需要添加conductor1=conductor1->next1;
在分配新節點以在每次迭代中前進到下一個節點之后。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.