Skip to main content

Program to create a Linked List in C

An array is a commonly used data structure in most of the languages. Because it is simple, it needs O(1) time for accessing elements. It is also compact.

But an array has a serious drawback - it can not grow or shrink. You need to estimate the array size and define it during compile time.

This drawback is not present a linked list. A linked list is a data structure which can grow or shrink dynamically. 

A linked list has nodes each of which contain  contain  data and a link to next node. These nodes are dynamically allocated structures. If you need more nodes, you just need to allocate memory for these and link these nodes to the existing list.

The nodes of a linked list have to be defined as self-referential structures in C. That is structures with data members and one member which is a pointer to the structure of same type.  This pointer will work as a link to next node.

struct node
{
 int data;
 struct node *next;//pointer to another node
};
typedef struct node * NODEPTR;

Of course we can work without creating the typedef. But typedef makes code more elegant. We will  use this NODEPTR. Allocate memory for it, then populate it and finally link it.
 
A linked list must have a starting node called head node or start node which will be the pointer to first node of the list. Any operation to the list needs this head. This head has to maintained because if the program overwrites this pointer, the list will be lost.  We should initialize head with NULL because initially the list is empty.

NODEPTR head = NULL;
First let us write a function to create a new node, assign values to the data of this node and return pointer to this node.


 NODEPTR create_node(int value)  
 {  
   NODEPTR temp = (NODEPTR) malloc(sizeof(struct node));  
    temp->next = NULL;  
   temp->n = value;  
   return temp;  
 } 

Now to add nodes to this list, let us write a function which takes head as a parameter and data for the new node as second parameter. The function will return the head pointer.


NODEPTR append_node(NODEPTR head,int val)
{
      NODEPTR newnode ;
      newnode = create_node(val);       
      
     /*find the last node in the linked list */
     for(temp = head; temp->next!=NULL;temp = temp->next)
     ;/*do not forget this semicolon*/
     /*link the new node to temp - the last node*/
     temp->next = newnode;
     return head;
}

We find the last node of the linked list by looping till temp->next =NULL. Then we link this last node to new node.

The function is fine for all nodes except the first node. When the list is empty and you want to add a node, you should not use the for loop to find the last node. Instead, if head is NULL, you should assign new node to head and return it.

NODEPTR append_node(NODEPTR head,int val)
{
      NODEPTR newnode ;
      newnode = create_node(val);
      /* if the list is empty*/
      if (head==NULL)
         head = newnode;
      else{ 
          for(temp = head; temp->next!=NULL;temp = temp->next)
              ;
         temp->next = newnode;
     } 
   return head;
}

And now we have to test this function. Let us also write a function to traverse the list and print it. This function is quite simple


void print_list(NODEPTR head)
{
     NODEPTR temp = head;
     while(temp!=NULL)
      {
             printf("%d---->",temp->data);
             temp = temp ->next;
      }
}

Let us use these functions and write the complete program

#include<stdio.h>
struct node
{
 int data;
 struct node *next;
};

typedef struct node * NODEPTR;
 
 NODEPTR create_node(int value)  
 {  
   NODEPTR temp = (NODEPTR) malloc(sizeof(struct node));  
    temp->next = NULL;  
   temp->n = value;  
   return temp;  
 } 
 NODEPTR append_node(NODEPTR head,int val)
{
     NODEPTR newnode,temp ;
      newnode = create_node(val);
     /*if the list is empty , assign newnode to head*/
     if(head ==NULL)
     {
        head = newnode;
        return head;
     }
    /*find the last node in the linked list */
     for(temp = head; temp->next!=NULL;temp = temp->next)
     ;/*do not forget this semicolon*/
     /*link the new node to temp - the last node*/
     temp->next = newnode;
     return head;
}

void print_list(NODEPTR head)
{
     NODEPTR temp = head;
     while(temp!=NULL)
      {
             printf("%d---->",temp->data);
             temp = temp ->next;
      }
}

int main()
{
   NODEPTR head = NULL;
   int i;
   for(i = 0;i<10;i++)
   {
       int n;
       printf("Enter a number :");
       scanf("%d",&n);
       head = append_node(head,n);
    }
    printf("The list is :");
    print_list(head);
}

Compile and run this program . Here is how your output looks like.


If you are curious and want to know how these links are working and modify the printf in the print_list function.

           printf("temp=%p  temp->data=%d temp->next=%p\n;",temp,temp->data,temp->next);

Now with this change, your output may look like

So our first program on linked list is ready. In the next post we will see how to delete a node from linked list and how to search for a value in the list.

Comments

  1. Hey there! Do you use Twitter? I'd like to follow you if that would be okay.

    I'm absolutely enjoying your blog and look forward to new updates.


    my site ... homepage ()

    ReplyDelete

Post a Comment

Popular posts from this blog

Introduction to AVL tree

AVL tree is a balanced binary search tree where the difference between heights of two sub trees is maximum 1. Why balanced tree A binary tree is good data structure because search operation here is of the order of O(logn). But this is true if the tree is balanced - which means the left and right subtrees are almost equal in height. If not balanced, search operation will take longer.  In worst case, if the tree has only one branch, then search is of the order O(n). Look at this example.  Here all nodes have only right children.  To search a value in this tree, we need upto 7 iterations, which is O(n). So this tree is very very inefficient. One way of making the tree efficient is to, balance the tree and make sure that height of two branches of each node are almost equal. Height of a node Height of a node is the distance between the node and its extreme child.  In the above a diagram, height of 37 is 3 and height of left child of 37 is 0 and right child of 37 is 2. Bal...

Reverse a singly linked list

One of the commonly used interview question is - how do you reverse a linked list? If you talk about a recursive function to print the list in reverse order, you are so wrong. The question is to reverse the nodes of list. Not print the nodes in reverse order. So how do you go about reversing the nodes. You need to take each node and link it to previous node. But a singly linked list does not have previous pointer. So if n1 is current node, n2 = n1->next, you should set     n2->next = NULL But doing this would cut off the list at n2. So the solution is recursion. That is to reverse n nodes  n1,n2,n3... of a list, reverse the sub list from n2,n3,n4.... link n2->next to n1 set n1->next to NULL The last step is necessary because, once we reverse the list, first node must become last node and should be pointing to NULL. But now the difficulty is regarding the head? Where is head and how do we set it? Once we reach end of list  viz n1->next ==NULL, th...

Balanced brackets

Have you observed something? When ever you are writing code using any IDE, if you write mismatched brackets, immediately an error is shown by IDE. So how does IDE  know if an expression is having balanced brackets? For that, the expression must have equal number of opening and closing brackets of matching types and also they must be in correct order. Let us look at some examples (a+b)*c+d*{e+(f*g)}   - balanced (p+q*[r+u )] - unbalanced (p+q+r+s) ) - unbalanced (m+n*[p+q]+{g+h}) - balanced So we do we write a program to check if an expression is having balanced brackets? We do need to make use of stack to store the brackets. The algorithm is as follows Scan a character - ch from the expression If the character is opening bracket, push it to stack If the character is closing bracket pop a character from stack If popped opening bracket and ch are not of same type ( ( and ) or [ and ] ) stop the function and return false Repeat steps 2 and 3 till all characters are scanned. On...