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

Delete a node from doubly linked list

Deletion operation in DLL is simpler when compared to SLL. Because we don't have to go in search of previous node of to-be-deleted node.  Here is how you delete a node Link previous node of node of to-be-deleted to next node. Link next node of node of to-be-deleted to previous node. Free the memory of node of to-be-deleted Simple, isn't it. The code can go like this. prevnode = delnode->prev; nextnode = delnode->next; prevnode->next = nextnode; nextnode->prev = prevnode; free(delnode); And that is it. The node delnode is deleted. But we should always consider boundary conditions. What happens if we are trying to delete the first node or last node? If first node is to be deleted, its previous node is NULL. Hence step 3 should not be used.  And also, once head is deleted, nextnode becomes head . Similarly if last node is to be deleted, nextnode is NULL. Hence step 4 is as strict NO NO. And we should set prevnode to tail. After we put these things together, we have...

Function to sort an array using bubble sort

Quick and dirty way of sorting an array is bubble sort. It is very easy to write and follow. But please keep in mind that it is not at all effecient. #include<iostream> using std::cin; using std::cout; void readArray(int arr[],int sz); void printArray(int arr[],int sz); void sortArray(int arr[],int sz); void swap(int &a,int &b); int main() {    int sz;    cout<<"Size of the array=";    cin>>sz;    int arr[sz];    readArray(arr,sz);     sortArray(arr,sz);   cout<<"Sorted array is ";   printArray(arr,sz); } void readArray(int arr[],int sz) {  for(int i=0;i<sz;i++)    {       cout<<"arr["<<i<<"]=";       cin>>arr[i];   } } void printArray(int arr[],int sz) {  for(int i=0;i<sz;i++)    {       cout<<"arr["<<i<<"]=";    ...

Merge two binary search trees

How do you merge two binary search trees? I googled about the solutions. Most solutions told me to convert both trees into linked lists. Merge the lists. Then create a tree from the elements of the list. But why lists? Why can't we store the elements in an array? Because if the data of the tree is larger - not just integer keys, array manipulation becomes difficult. But again, we need not convert both the trees into lists. We can convert one tree into list - a doubly linked list. Then insert the elements of this list into the other tree. I tried this approach. To convert a tree into a sorted doubly linked list Create a doubly linked list. Let the prev and next links of nodes in this list be called left and right respectively. This way we can directly use the binary tree nodes in the list. Use a static variable previousnode  call the function recursively for left child of current node. link current node to the previousnode set next pointer of previousnode to curre...