Error in Linked List

C

chellappa

hi
this is linked list program ,,,
this program display in reverse order...........
how to correct this error

#include <stdio.h>
struct list {
int value;
struct list *next;
};

main()
{
struct list *n1;
struct list *head =NULL;
int i;
head =n1;
for (i=0;i<10;i++)
{
n1=(struct list *)malloc(sizeof(struct list));
n1->value=i;
n1->next=head;
head=n1;
}
while( head != NULL )
{
printf("%d\n", head->value);
head = head->next;
}
}

Thank U
By
CNS
 
N

Nick Keighley

chellappa said:
this is linked list program ,,,
this program display in reverse order...........
how to correct this error

add items at the end instead of the beginning. Add a tail pointer that
always points at the last item.

#include <stdio.h>

struct list {
int value;
struct list *next;
};

main()

that's "int main (void)"

{
struct list *n1;

what is n1 pointing at?
struct list *head =NULL;
int i;
head =n1;

what is head pointing at?
for (i=0;i<10;i++)
{
n1=(struct list *)malloc(sizeof(struct list));

don't cast the return value of malloc()
n1->value=i;
n1->next=head;
head=n1;
}
while( head != NULL )
{
printf("%d\n", head->value);
head = head->next;
}

return 0;
 
C

Chris Dollin

Nick said:
add items at the end instead of the beginning. Add a tail pointer that
always points at the last item.

Or reverse the list (easy) when you've finished constructing it.
 
M

Martin Ambuhl

chellappa said:
hi
this is linked list program ,,,
this program display in reverse order...........
how to correct this error

*These* errors, including huge errors in program logic.
Try this for a starting point (OP's code at EOM)

#include <stdio.h>
#include <stdlib.h>
struct list
{
int value;
struct list *next;
};

int main(void)
{
struct list *n1, *last = 0;
struct list *head = 0;
int i;
for (i = 0; i < 10; i++, last = n1) {
n1 = malloc(sizeof *n1);
/* mha: add error handling here */
if (!head)
head = n1;
else
last->next = n1;
n1->value = i;
n1->next = 0;
}
for (n1 = head; n1; n1 = n1->next)
printf("%d\n", n1->value);
return 0;
}


[OP's code]
#include <stdio.h>
struct list {
int value;
struct list *next;
};

main()
{
struct list *n1;
struct list *head =NULL;
int i;
head =n1;
for (i=0;i<10;i++)
{
n1=(struct list *)malloc(sizeof(struct list));
n1->value=i;
n1->next=head;
head=n1;
}
while( head != NULL )
{
printf("%d\n", head->value);
head = head->next;
}
}

Thank U
^^^
Don't do this. It makes you look like a child. There are many things
done by non-native English writers that go unremarked, but SMS
abbreviations are not among them.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,918
Members
47,458
Latest member
Chris#

Latest Threads

Top