Tuesday, August 21, 2012

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);
}

Wednesday, February 15, 2012

constructor overloading in c++

Constructor play an important part in c++. They can initialize the values of a given object to some known values. This is important as constructor will be able to set some values in objects which otherwise may have some garbage values. Most uninitialized value in objects are main cause of the bugs.
But the concept of constructor can allow us to do just anything beside initializing values. Constructor are always called when an object is created. This property of constructor is very useful in situation when you need to perform some task as soon as an object is created.
So constructor is a special function that gets called automatically when an object is created. This function can like any other function do anything (like initializing values).
Overloading Constructor :
This process is very similar to the overloading of simple functions. Since constructor are also function , they can be overloaded like any other functions. This allows user to create many constructor, which can help user to create (and set) objects differently. In most cases objects have data member set to private (so user can't directly change the values of the objects). Different constructor can allow creation of objects with desired type of values.
Method :
Overloading a constructor is very similar to function overloading. Just change the signature (no. of args and type of args) of the constructor.
Overloaded Constructor Usage::
<class name> <objectname>(args);
like Box b; or Box b2(9);

Code:


#include<iostream>

using namespace std;

class box
{
    //data member  are private
    int width,height,length;
    
    public:
    
    box()
    {
        //default constructor 
        //initializes values to 0;
        width=height=length=0;
    }
    box(int k)
    {
        //overloaded constructor with one argument
        //will initialize all 3 data member to value 'k'
        width=height=length=k;
    }
    box(int x,int y,int z)
    {
        //overloaded constructor with 3 argument
        //will initialize data member differently
        width=x;
        height=y;
        length=z;
    }
    void show()
    {
        //function to show these values
        cout<<"\n Width="<<width;
        cout<<"\n Height="<<height;
        cout<<"\n Length="<<length;
    }
    
};

int main()
{
    box b;//using default constructor
    box b2(9);//using 1st overloaded constructor
    box b3(1,2,3);//using 2nd overloaded constructor
    
    b.show();
    b2.show();
    b3.show();
}

Wednesday, January 11, 2012

Bubble Sort in C++ with improvements

Here is an example of Bubble sort in C++.  The example will perform bubble sort on a set of 10 integers. The example is a OO example . So everything is in a class called bubble. The class it self has following methods in it.

Sunday, January 8, 2012

Find Armstrong Number in C

Finding Armstrong number is again a great exercise for students The exercise involves clever use of modulus operator to extract the digits and then using those digits to perform calculations.

Tuesday, January 3, 2012

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;
        //default constructor
    }
    vector(int a, int b,int c)
    {
        x=a;y=b;z=c;
    }
    void show()// to show vector
    {
        cout<<"\n Vector="<<x<<"i+"<<y<<"j+"<<z<<"k";
    }
    //the operator overloading returns a vector
    //although return type can be anything
    vector operator~()
    {
        //notice how the ans object is being created
        // we are passing it the value by our constructor
        vector ans(z,y,x);
        return(ans);
    }
};

int main()
{
    //create 2 vector
    // one has value i+2j+3k other is 0
    vector v(1,2,3),c;
    //use ~ operator to reflect the vector and pas it to c
    c=~v;
    v.show();
    c.show();
    
}