Monday, September 17, 2012

Why use double pointer when adding node to Linked List?

Why use double pointer when adding node to Linked List? This question struck my mind when i first read about Linked Lists in my Second Semester. At that time i didnt gave it much thought. But from past 1 week i wanted the answer of this question. I googled it, but forums were full of nasty definitions of pointers and their usage, asked my seniours but they told me the bookish reasons which didnt made me satisfied, so i decided to do some experiments and make some conclusion......

OBSERVATION 1- If the linked list is not empty then we can add the nodes in it (obviously at the end) by using a single pointer only.

int insert(struct LinkedList *root, int item)
{
    struct LinkedList *temp;
    temp= (struct LinkedList *)malloc(sizeof(struct LinkedList));
    temp->data=item;
    temp->next=NULL;
    struct LinkedList *p;
    p=root;
    while(p->next!=NULL)
    {
        p=p->next;
    }
    p->next=temp;
    return 0;
}


int main()
{
    int m;

    struct LinkedList *A;

    A=(struct LinkedList *)malloc(sizeof(struct LinkedList));
    //now we want to add one element to the list so that the list becomes non-empty
    A->data=5;
    A->next=NULL;
    cout<<"enter the element to be inserted\n";
    cin>>m;
    insert(A,m);
    return 0;
}


Its simple to explain. We have a pointer in our main function which points to the first node (or root) of the list. In the insert() function we pass the address of the root node and using this address we reach the end of the list and add a node to it. So we can conclude that if we have address of a variable in a function (not the main function) we can make permanent changes in the value of that variable from that function which would reflect in the main function.



OBSERVATION 2- The above method of adding node failed when the list was empty.


int insert(struct LinkedList *root, int item)
{
    struct LinkedList *temp;
    temp= (struct LinkedList *)malloc(sizeof(struct LinkedList));
    temp->data=item;
    temp->next=NULL;
    struct LinkedList *p;
    p=root;
    //check if list is empty
    if(p==NULL)
    {
        p=temp;
    }
    else
    {
      while(p->next!=NULL)
      {
          p=p->next;
      }
      p->next=temp;
    }
    return 0;
}



int main()
{
    int m;

    struct LinkedList *A;

    A=NULL;//initialise the list to be empty
    cout<<"enter the element to be inserted\n";
    cin>>m;
    insert(A,m);
    return 0;
}


If you keep on adding elements and finally display the list then u would find that the list has undergone no changes and still it is empty.
The question which struck my mind was in this case also we are passing the address of the root node then why modifications are not happening as permanent modifications and list in the main function undergoes no changes. WHY? WHY? WHY? 
Then i observed one thing, when i write A=NULL the address of A becomes 0. This means now A is not pointing to any location in memory. So i removed the line
A=NULL; and made some modification in the insert function... 





some modifications......(below insert() function can add only one element to an empty list,, just wrote this function for testing purpose)




int insert(struct LinkedList *root, int item)
{
    root= (struct LinkedList *)malloc(sizeof(struct LinkedList));
    root->data=item;
    root->next=NULL;
    return 0;
}



int main()
{
    int m;

    struct LinkedList *A;
    cout<<"enter the element to be inserted\n";
    cin>>m;
    insert(A,m);
    return 0;
}

the above method also fails because in the insert() function root stores same address as A in the main() function but after the line root= (struct LinkedList *)malloc(sizeof(struct LinkedList)); the address stored in root changes. Thus ,now , root (in insert() function) and A (in main() function)  store different addresses.

SO THE CORRECT FINAL PROGRAM WOULD BE...


int insert(struct LinkedList *root, int item)
{
    root->data=item;
    root->next=NULL;
    return 0;
}



int main()
{
    int m;

    struct LinkedList *A;
    A= (struct LinkedList *)malloc(sizeof(struct LinkedList));
    cout<<"enter the element to be inserted\n";
    cin>>m;
    insert(A,m);
    return 0;
}

But we dont want two different functions for insertion , one when list is empty and other when list is not empty. Now comes double pointer which makes things easy.

now pls give ur full attention,
lets see what double pointer can do,

ONE THING I NOTICED WHICH IS IMPORTANT IS THAT POINTERS STORE ADDRESS AND WHEN USED WITH '*' THEY GIVE VALUE AT THAT ADDRESS BUT POINTERS THEMSELVES HAVE THEIR OWN ADDRESS.
for example-
if we write int *a,p; a=&p; then *a would give value of p, a would give address of p, and &a would give address of pointer a.

now i would first give the complete program and then explain the concepts.....


int insert(struct LinkedList **root,int item)
{
    if(*root==NULL)
    {
        (*root)=(struct LinkedList *)malloc(sizeof(struct LinkedList));
        (*root)->data=item;
        (*root)->next=NULL;
    }
    else
    {
        struct LinkedList *temp=(struct LinkedList *)malloc(sizeof(struct LinkedList));
        temp->data=item;
        temp->next=NULL;
        struct LinkedList *p;
        p=*root;
        while(p->next!=NULL)
        {
            p=p->next;
        }
        p->next=temp;
    }
    return 0;
}


int main()
{
    int n,m;
    struct LinkedList *A=NULL;
    cout<<"enter the no of elements to be inserted\n";
    cin>>n;
    while(n--)
    {
        cin>>m;
        insert(&A,m);
    }
    display(A);
    return 0;
}



following are the observations->
1. root stores the address of pointer A (&A) , *root stores the address stored by pointer A and **root stores the value at address stored by A. In simple language root=&A, *root= A and **root= *A.
2. if we write *root= 1528 then it means that value at address stored in root becomes 1528 and since address stored in root is the address of pointer A (&A) thus now A=1528 (i.e. address stored in A is 1528) and this change is permanent.

 whenever we are changing value of *root we are indeed changing value at address stored in root and since root=&A ( address of pointer A)  we are indirectly changing value of A or address stored in A.

so now if A=NULL (list is empty) *root=NULL , thus we create the first node and store its address at *root  i.e. indirectly we storing the address of first node at A. If list is not empty , everything is same as done in previous functions using single pointer except we have changed root to *root since what was stored in root is now stored in *root.



Thursday, September 13, 2012

Kudiyo ke Nakhre.....




moh maaya me kyu phaste ho tum,
uski adaao pe kyu marte ho tum,
aamir khan ki kahi baat bhul gaye kya,
bus,train to thik h magar uske nakhro ko kyu sehan karte ho tum.

din raat padh kar bhi wo jitna nahi janti,
bina padhe usse jyada jaante ho

 tum,
khud ko bada creative samajhti h wo,
lekin innovation ke maamle me unke baap ho tum.

ek dusre ko saali , kutti , kamini bol kar
sochti h Oh my God aaj to kuch jyada hi bol diya,
unhe kya pata jo wo soch bhi nahi sakti
usse bhi achi gaaliyo ke inventor ho tum.

ghanto make up karke jitna chamakti h wo,
bina nahaye usse jyada chamakte ho tum,
8 ghante sone ke baad bhi kehti h i am sleepy,
3 ghanta so kar bhi padhai plus masti karte ho tum.

40 km/hr par scooty kya chala li,
khud ko samajhti h Rani Lakshmi Bai,
R.S. ke 2 pack aur sutta lagane ke baad bhi,
90 ki speed pe bike chalate ho tum.

2-4 comment kya maar diye,
bolti h wo tumko character less,
lekin train me waiting ticket me jab seat nahi milti,
to character less se unke best friend ban jaate ho tum.

moh maaya me kyu phaste ho tum,
uski adaao pe kyu marte ho tum,
aamir khan ki kahi baat bhul gaye kya,
bus,train to thik h magar uske nakhro ko kyu sehan karte ho tum.

Sunday, May 13, 2012

Still Suffering.....














socha tha 1st Year me kar lo thodi padhai,
 2nd year me to karna h bhot aaram,
magar kitni galat soch thi meri,
4th sem me ho gaya h jeena haraam.


kal tak sirf Counter Strike ke liye use kiya karte the computer ki hard disk aur RAM,
aaj usi computer pe compile karte h Heapsort aur Binary tree ke programs,
proxy banane ke alawa aur kuch bhi nahi aata tha,
ab Resume bhi likh lete h , A very big thanks to english waali maam,

padh padh kar Discrete Maths ke algebraic structure
ho gaye hum Total ghanchakkar,
padh kar computer ke bits and bytes,
badal gaya h dimag ka Memory Structure.


padh-padh kar Phonetics ban gaye hum total angrez,
hindi to bhul hi gaye h, chad gaya h videshi bhashao ka craze,

Recursive tree ke recursion ne , kar diya life ka destruction,
bolne ko kuch bacha nahi, But we are supporting Anna against corruption.

padh lo Cormen samaj me aa jayega Algorithm and Shortest path,
darne ki kya h baat jab tak uparwale ka h apne sir pe hath,
aur ho sakta h humari branch me bhi mass bunk,
bas mil jaye ek baar branch ke toppers ka sath,...............


Copyright © 2012 Piyush Golani All Rights Reserved

Saturday, May 12, 2012

The Facebook Fever


socha tha garmiyo ki chuttiyo me padhunga C++ ki book,
lekin subah hote hi computer par khul jata h facebook..
Notifications me hi duniya simat gayi h meri,
frustration mein i give myself a very dirty look...

koi likhta h LOVE is everything,
koi likhta h Love is fake,
aur koi likhta h Janu wapas aa jao,...
i wanna dive into your eyes.. coz ur eyes are much deeper than a lake...

dost hua from 'Single' to 'In a relationship'
aur likha 'I cant live without seing her face'..
2 weeks later back from 'In a relationship' to 'Single'
aur likha 'she took from me my freedom and space'...

jo bhi kaho Facebook made my mind fully paralysed and lame,
but still i get very happy when in the chat box ,
i see a green dot beside her name.. ;-)



Copyright © 2012 Piyush Golani All Rights Reserved

Getting started on Topcoder..


hey guys, this post is about how to get started on one of the biggest coding site Topcoder. You must have observed that this is not an ordinary coding site like codechef and codeforces where you can just open a problem and submit your solution. This is because of the following two reasons.....

1. Topcoder has a java applet called Arena on which you can write your code and after then compile and test your code against the various test cases.

2. Topcoder allows only Object-Oriented Languages like C++, Java, C99 etc . This means that if you are a C coder then you must shift to C++ in order to compete on topcoder.

Before beginning let me tell you that topcoder hosts a number of Algorithmic competitions and the most common among them are SRMs (Single Round Matches)...

Now do the following steps........

1. Open the Topcoder website.

2. Register yourself on the site. If you are already registered then simply click on the 'Go to Community Portal' link on the top-right of the page.

3. Now on the top-left corner of the new page you would observe a lot of symbols... Click on 'O(n)' symbol. when u place your mouse pointer on it you would see 'Algorithm Competitions' appearing below.

4. On the new window click on the red button which says 'Load Competition Arena'. A '.jnlp' file would be downloaded. Now Launch this Java file and after a few seconds you would notice a beautiful arena appearing on your screen..

5. Simply enter your Username and Password and click on the 'go' button. Now you are ready to code, practise and compete.  Below picture shows a view of the Arena after you login in.....


Now i would suggest you to observe the various functionalities of the Arena by clicking on various buttons..

Do write your comments below and dont forget to click on the 'g+' button if u liked the post.......

Senior hai Duffer...



pee rahi thi Maaza jab tum khadi sudha pe,

dekhkar upar kaha meine khuda se,

Oh my God banane me ise laga hoga aapko bhot time,

dekhkar adaye unki my heart feels so fine,

overflow karne laga tha mere dil ka buffer,


peeche se dost bola "Abe Senior h duffer",,,,,,,,,,,,,,


Copyright © 2012 Piyush Golani All Rights Reserved

Thursday, May 3, 2012

String to Int ----- Int to String (some functions and their uses)

In many programming problems the input is given in string format and we have to extract int values from that for our manipulation... also sometimes we have to output some int in the form of a string .... following are the methods by which this task can be accomplished.....

1. Conversion from string to int 
suppose we are given a string time= "20:12:33";
int hour,min,second;
sscanf(time.c_str(),"%d:%d:%d",&hour,&min,&second);
now after the execution of above statement ,
 hour= 20, min= 12, second= 33

2. Conversion from string to int (when string is a set of two or more space separated strings)
suppose we have a string info= "Alice 20 M 125";
the above string consists of three strings(space separated) "Alice" , "20", "M", "125"
firstly include a header file..... #include<sstream>
make a declaration in your code istringstream is(info);
the example is shown below.....
#include<iostream>
#include<sstream>

void demo(string info)
                                                               {
istringstream is(info);
string name;
int age , id;
char sex;
is>>name; // name= Alice
is>>age; // age=20
is>>sex; // sex= M
is>>id; //id= 125
                                                                }


3. Conversion from int to string 
include a header file #include<sstream>,
example is shown below.......
#include<iostream>
#include<sstream>

                                                            void demo()
                                                           {
int hh=10, mm= 9, ss= 23;
                                                            stringstream t;
                                                            string time;
                                                            t<<hh<<":"<<mm<<":"<<ss;
                                                            time= t.str();// time= "10:9:23"
                                                            }



4. snprintf() in c++
#include<iomanip>
int totalrank=5;
double total= 234;
string name= "Piyush";
char buf[150];
vector<string> ans;
ans.clear();
snprintf(buf , sizeof(buf) , "%s %d %0.1f", name.c_str() , totalrank , total);
ans.push_back(buf);
cout<<ans[0];
the output would be......
Piyush 5 234.0