EmbLogic's Blog

Linked List

The following code is meant to create a Linked List. The code is running  and it shows no error. Is this the correct way of creating a linked list….????

1
2
3 #include<stdio.h>
4 #include <stdlib.h>
5 struct node
6 {
7         int info;
8         struct node *ptr;
9 };
10 struct node *start,*temp;
11
12 //*temp=*start=(struct node*)malloc(sizeof(struct node))
13
14 int main()
15 {
16         int i;
17         start=temp=(struct node*)malloc(sizeof(struct node));
18
19         for(i=0 ; i <3 ; i++)
20                 {
21                 temp=(struct node*)malloc(sizeof(struct node));
22                 temp=temp->ptr;
23                 }
24         return 0;
25 }

3 Responses to Linked List

  1. u are reallocating the temp ,so ur starting pointer start and temp points to two different pointers and ur code should be look like this
    main()
    15 {
    16 int i;
    17 start=temp=(struct node*)malloc(sizeof(struct node));
    18
    19 for(i=0 ; i ptr=(struct node*)malloc(sizeof(struct node));
    22
    23 }
    24 return 0;
    25 }

  2. ignore the above code its wrong…
    int main()
    15 {
    16 int i;
    17 start=temp=(struct node*)malloc(sizeof(struct node));
    18
    19 for(i=0 ; i ptr=(struct node*)malloc(sizeof(struct node));
    22
    23 }
    24 return 0;
    25 }

  3. i thought its problem on blog its not working properly
    add only this statement inside ur loop
    temp->ptr=(struct node*)malloc(sizeof(struct node));
    and add any thing in ur info field by scanf
    into
    temp->info=info type variable;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>