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...

Binary tree deletion - non-recursive

In the previous post we have seen how to delete a node of a binary search tree using recursion. Today we will see how to delete a node of BST using a non-recursive function. Let us revisit the 3 scenarios here Deleting a node with no children just link the parent to NULL Deleting a node with one child link the parent to  non-null child of node to be deleted Deleting a node with both children select the successor of node to be deleted copy successor's value into this node delete the successor In order to start, we need a function to search for a node in binary search tree. Did you know that searching in  a BST is very fast, and is of the order O(logn). To search Start with root Repeat until value is found or node is NULL If the search value is greater than node branch to right If the search value is lesser than node branch to left.  Here is the function NODEPTR find_node (NODEPTR root,NODEPTR * parent, int delval) { NODEPTR nd = root; NODEPTR pa = root; if (ro...

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<<"]=";    ...