Reputation: 165
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. In the following code, I am trying to print what I put in the first list, reading with 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
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;
}
Upvotes: 1
Views: 159
Reputation: 110108
In the for
loop you are never changing the value of 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;
after allocating the new node to advance to the next node in each iteration.
Upvotes: 3