Tuesday, December 10, 2013

Back To Primitive Code: Creating a Linked List


The below code explains procedure to how to create a Singly-Linked-List and Print Data in that List.

#include <stdio.h>

/*This part of the code is to create a structure in which we create the simplest entity in the List which is a Node
 <Code below is definition of single Node>
The Node consists of the internal Data which can be anything from primitive data to an array to another structure.
*/
struct Node
{
    int info;
    struct Node *next;
};

/*Now to create a linked list what we require is a HEAD to mark the beginning of the Linked-List followed by a TEMP to track the current node being processed, followed by a Temp Definition of NEWNODE which will be created at run-time*/

int main()
{
    int i = 0;
    struct Node *head = (struct Node*)malloc(sizeof(struct Node));
    struct Node *temp = NULL;  
    struct Node *newnode = NULL;  


    for(i = 0 ;i < 10;i++)
    {
        newnode = (struct Node*)malloc(sizeof(struct Node));
        newnode->info = i;
        newnode->next = NULL;
        
        if(i == 0)
        {
            head->info = -1;        /*This Condition will be satisfied only once i.e for the First Node*/
            head->next = newnode;
        }
        else if(i > 0 && i < 10)
        {
            temp->next = newnode;
        }
        temp = newnode;
    }
/*This part of the code to traverse the whole list and Print all Info Data in each Node*/
    printf("Print Link List\n");
    
    temp = head;
    while(temp->next != NULL)
    {
        printf("%d\n",temp->info);
        temp = temp->next;
    }
   return 0; 
}

Code Test Run made on : http://codepad.org/ C Compiler

No comments:

Post a Comment