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

Linked list in C++

A linked list is a versatile data structure. In this structure, values are linked to one another with the help of addresses. I have written in an earlier post about how to create a linked list in C.  C++ has a library - standard template library which has list, stack, queue etc. data structures. But if you were to implement these data structures yourself in C++, how will you implement? If you just use new, delete, cout and cin, and then claim it is your c++ program, you are not conforming to OOPS concept. Remember you have to "keep it together". Keep all the functions and variables together - in a class. You have to have class called linked list in which there are methods - append, delete, display, insert, find, find_last. And there will also be a data - head. Defining node We need a structure for all these nodes. A struct can be used for this purpose, just like C. struct node { int val; struct node * next; }; Next we need to define our class. W

Swap nodes of a linked list

Qn: Write a function to swap the adjacent nodes of a singly linked list.i.e. If the list has nodes as 1,2,3,4,5,6,7,8, after swapping, the list should be 2,1,4,3,6,5,8,7 Image from: https://tekmarathon.com Though the question looks simple enough, it is tricky because you don't just swap the pointers. You need to take care of links as well. So let us try to understand how to go about it. Take two adjacent nodes p1 and p2 Let prevnode be previous node of p1 Now link prevnode to p2 Link p2 to p1 Link p1 to next node of p2 So the code will be prevnode -> next = p2; p1 -> next = p2 -> next; p2 -> next = p1; But what about the start node or head? head node does not have previous node If we swap head with second node, modified head should be sent back to caller  To take care of swapping first and second nodes, we can write p1 = head; p2 = head -> next; p1 -> next = p2 -> next; p2 -> next = p1; head = p2;  Now we are read

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 (root -> v