Thread: How to create many nodes in list

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    129

    How to create many nodes in list

    I can create node one by one but I don't think this is efficient way to create link list

    I have created three node's in the program 1 2 3

    Code:
    #include<stdio.h>#include<stdlib.h>
    
    
    struct Node
    {
      int data;
      struct Node *next;
    };
      int main()
    {
      struct Node* head = NULL;
      struct Node* second = NULL;
      struct Node* third = NULL;
      struct Node *temp = NULL;
    
    
    
    
      head  = (struct Node*)malloc(sizeof(struct Node));
      second = (struct Node*)malloc(sizeof(struct Node));
      third  = (struct Node*)malloc(sizeof(struct Node));
     
      head->data = 1;       //assign data in first node
      head->next = second;  // Link first node with second
     
      second->data = 2;     //assign data to second node
      second->next = third;
     
      third->data = 3;     //assign data to third node
      third->next = NULL;
    
    
       temp = head;
      while (temp != NULL)
      {
         printf(" %d ", temp->data);
         temp = temp->next;
      }
      
      return 0;
    }
    I am looking help to create 100 numbers in the list

    I think I can use for loop

    Code:
    for ( i = 0, i <100; i++)
    
    {
      //code here
    }
    How to create 100 numbers in the list

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The problem is that if you're only keeping track of the head, it's rather inefficient to append to the linked list in a loop as you have to keep traversing the entire linked list on each iteration.

    The solution is to keep track of both head and tail. Initially, they are both null pointers. When the very first node is added, the head and tail pointers both point to that on. On the second and subsequent nodes, the tail node's next pointer is set to point to the new node (with a null next pointer, of course), and then the tail pointer itself is set to point to the new node, thereby appending to the linked list in constant time while keeping track of the tail.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2018
    Location
    Amberg in upper palatinate, Bavaria
    Posts
    66
    Hallo abhi143!

    I hope the example below will give you some inspirations:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
     struct node {
      int x;
      struct node *next;
    };
     
    int main(int argc, char **argv) 
    {
        int i = 3; // gets later an another value
        
        /* This won't change, or we would lose the list in memory */
        struct node *root;       
        /* This will point to each node as it traverses the list */
        struct node *conductor;  
        struct node *temp = NULL;
     
        //root = malloc( sizeof(struct node) );  
        root = (struct node*)malloc(sizeof(struct node));
        root->next = 0;   
        printf( "Enter a integer. ");
        scanf("%d", &root->x); // = 12;
        conductor = root; 
    for (i = 0; i < 4; i++) 
    {
       if ( conductor != 0 ) 
         {
          while ( conductor->next != 0)
           {
            conductor = conductor->next;
           }
         }
       
      /* Creates a node at the end of the list */
        conductor->next = (struct node*)malloc(sizeof(struct node));  
     
        conductor = conductor->next; 
     
        if ( conductor == 0 )
         {
          printf( "Out of memory" );
          return 0;
         }
        if ( conductor != 0 )
         { /* Makes sure there is a place to start */
          while ( conductor->next != 0 )
           {
            printf( "Value: %d\n", conductor->x );
            conductor = conductor->next;
    
      
           }
          printf( "%d\n", conductor->x );
        }
        /* initialize the new memory */
        conductor->next = 0;         
        printf( "Enter a integer. ");
        scanf("%d", &conductor->x); // = 42;    conductor->x = 42;
    }
      /*-----------------------Liste zeigen----------------------------*/
      
       temp = root;
    
       printf("Show the list:\n");
    
       while (temp != NULL)
        {
         printf(" %d ", temp->x);
         temp = temp->next;
        }
      
     
       printf("\nEnd of program\n");
     
        return 0;
    }

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You might want to test your code before posting as from what I can see, the code prefaced by the comment "Makes sure there is a place to start" has bugs because it accesses conductor->next and conductor->x before they have been set with their initial values. Recall that malloc doesn't necessarily zero the memory allocated. Frankly, you can get rid of that part entirely, and likewise the code that searches for the end of the linked list at the start of the loop: you already know for sure that you're at the end.

    Keeping to the same output as your example program but with more graceful error checking and without the unnecessary output of the pre-initial-value, what I had in mind was more along these lines:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    struct node
    {
        int x;
        struct node *next;
    };
    
    int read_int(int *result)
    {
        char buffer[BUFSIZ];
        return fgets(buffer, sizeof(buffer), stdin) && sscanf(buffer, "%d", result) == 1;
    }
    
    struct node *linked_list_populate(int n)
    {
        struct node *head = NULL;
        struct node *tail = NULL;
        for (int i = 0; i < n; i++)
        {
            struct node *new_node = malloc(sizeof(*new_node));
            if (!new_node)
            {
                fprintf(stderr, "Out of memory\n");
                break;
            }
            new_node->next = NULL;
    
            if (head)
            {
                tail->next = new_node;
                tail = new_node;
            }
            else
            {
                head = tail = new_node;
            }
    
            do
            {
                printf("Enter an integer. ");
            }
            while (!read_int(&tail->x));
        }
        return head;
    }
    
    void linked_list_print(struct node *head)
    {
        while (head)
        {
            printf(" %d ", head->x);
            head = head->next;
        }
    }
    
    void linked_list_destroy(struct node *head)
    {
        while (head)
        {
            struct node *next = head->next;
            free(head);
            head = next;
        }
    }
    
    int main(void)
    {
        struct node *head = linked_list_populate(5);
    
        printf("Show the list:\n");
        linked_list_print(head);
        printf("\nEnd of program\n");
    
        linked_list_destroy(head);
        return 0;
    }
    Although I might wrap head and tail in a struct linked_list instead, should it be useful to continue to keep track of the tail after populating the linked list.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 10-19-2015, 07:23 AM
  2. How can I create an array of nodes
    By skynet0928 in forum C++ Programming
    Replies: 7
    Last Post: 02-11-2015, 11:44 AM
  3. Linked list and nodes
    By Lina_inverse in forum C Programming
    Replies: 2
    Last Post: 10-23-2012, 01:59 PM
  4. Adding nodes to a list
    By Mentallic in forum C Programming
    Replies: 2
    Last Post: 09-06-2012, 12:29 AM
  5. List of nodes
    By spidereen in forum C++ Programming
    Replies: 1
    Last Post: 03-05-2003, 08:51 AM

Tags for this Thread