Skip to main content

Linked list using C

This is a Program for Linked List using C. The Code contains enough comments to make your life easy.


#include <stdio.h>


// structure to hold our data
// we call it node
// has a int 'value'
// also has a pointer that points to next node
struct node
{
    int value;
    struct node * next;
};
//typdef will save our time
//from now onwards 'struct node' will be replaced by NODE
typedef struct node NODE;


// you can notice that we are passing NODE** to insert
// Why????
// The answer is simple
// since we will be passing the head pointer to the function
// and head pointer can be modified in insertion operation
// so we must pass a NODE**
// reason being if we pass a NODE* to function
// its value will be restored after function has returned
// hence even if have modified head pointer, it will be restored
// so we pass NODE**
//------------------
// v is the value to be inserted

void insert(NODE** base, int v)
{
    NODE* BASE=*base;    // get pointer of head
    NODE* k;    // k will be used for allocation
    NODE* p=BASE; // p will be used like a temp pointer
    
    
    // if head pointer is NULL
    // means list is empty
    // so we will make a new node
    // attach head pointer to the new node
    if(*base==NULL)
    {
        printf("\nNo nodes in list, Adding first node with value=%d ",v);
        
        // alloc memory to k
        k=(NODE*)malloc(sizeof(NODE));
        
        // set values in node k
        k->value=v;
        // make its next pointer null
        k->next=NULL;
        //attach k to head node
        // notice since we have passed NODE**
        // we will use *base to get the value of the head node
        *base=k;
        // this is the only portion where head gets modified
        
    }
    else
    {
        // if head is not null
        // loop through list till we reach last node
        // last node can be checked by checking p->next value
        // if its not null we continue moving
        while(p->next!=NULL)
        {
            p=p->next;    
        }
        // ok now we are at last node
        printf("\n Adding another node with value=%d ",v);
        // create a new node on k
        k=(NODE*)malloc(sizeof(NODE));
        // do the usual stuff
        
        k->value=v;
        k->next=NULL;    
        // attach k to last node i.e. p
        
        p->next=k;
    }
    
    
    
}

//--- this function shows us the list
// we pass the head pointer to it and it shows us the list
void show(NODE* base)
{
    printf("\n List is= ");
    
    // if head node is NULL
    // means list is empty
    if(base==NULL)
    {
        printf("\nEmpty List");
    }
    else
    {
        // else loop through and print values along the way
        while(base!=NULL)
        {
            printf("%d,",base->value);
            base=base->next;
        }
    }
}

// del node can delete any value that is found first
// you can also see , we pass the NODE** to it 
// thats because deletion can even cause the head to be removed/ modified
// so address of the head is passsed to it
void del(NODE** base, int v)
{
    NODE* BASE=*base;// for our head pointer copy
    NODE* PRE=BASE;// another tmp pointer
    NODE* tmp; // one more tmp pointer
    
    // if head is empty 
    // we cant delete anything
    if(*base==NULL)
    {
        printf("\n Cant delete anything, List is empty");
    }
    // just in case the value to be deleted is on head !!
    // we move the head on to next node and free head
    else if((*base)->value==v)
    {
        printf("head node found, deleting");
        // copy head pointer to tmp
        tmp=*base;
        // move head to next node
        // notice the use of *base
        (*base)=(*base)->next;
        // free the previous head node
        free(tmp);
        
            
    }
    else
    {
        // node is somewhere along the way
        // lets find it
        // loop till you find the value
        // or we reach the last node
        while((BASE!=NULL) && (BASE->value!=v))
        {
            // copy BASE ptr value to pre
            // this is done so that we have a pointer to the last node
            // why we need previous node???
            // so that previous node can be linked to next node of the 'victim' node
            PRE=BASE;
            BASE=BASE->next;
        }
        // did we find the node??
        // if BASe is null , that means 
        // we failed to find the node
        if(BASE==NULL)
        {
            printf("\nNode Not Found !!");
        }
        else
        {
            // if base was not NULL that means we found the node
            printf("Deleting node......");
            // attach PRE's next pointer to BASE's next pointer
            // this will eliminate the link    
            PRE->next=BASE->next;
            // free the unlinked node
            free(BASE);
        }
        
    }
    
}

// our main
int main()
{
    // declare a head pointer
    NODE* base=NULL;// its NULL initially
    
    // insert some values
    // notice we pass the address of the head node
    insert(&base,5);
    insert(&base,6);
    insert(&base,7);
    insert(&base,8);
    // lets see what we have :)
    show(base);
    // now lets delete a value
    del(&base,9);
    // now lets see the list again
    show(base);
}

Popular posts from this blog

Find nth Prime Number in C++

c++ program to find prime numbers: The problem of finding prime number can be solved by checking all numbers, testing them for prime and then moving ahead. If you want to calculate nth prime. Then this can be done in a brutal way by checking the number one by one. This may sound odd, by there is no easy way then this  for prime numbers (Well Actually there are like Pollard's Rho Algorithm, Number Sieves or Shor's Quantum Algorithm, but we are talking about the one that most people may understand easily). There may be way to pre-calculate the prime numbers but that again is not sufficient. So how can we use c++ to create a program to find prime numbers.

Overloading Unary Operator in C++

In this Example I will demonstrate overloading a unary operator. The overloading is done in similar way as we did for binary operator. In this example I will be using a Vector Class. The operator we are going to over load is the unary "~" (tilde) operator. although you can use any unary overloadable operator. Method: In this example the overloaded operator will be the part of the class i.e. the over loaded definition will be a member function. (As we know overloading can be done using non member functions too). So the unary operator will not have any arguments in it. We will overload ~ operator so that it will reflect the vector so that its z component becomes x component and vice versa. So input vector will be 2i+3j+5k and its output vector will be 5i+3j+2k. although you can do anything you like. Code: # include < iostream > using namespace std ; class vector { int x , y , z ;      public : vector ( ) { x = y = z = 0 ; ...