Click here to Skip to main content
15,912,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote two codes to produce linked list.

One code uses insert function to form linked list.
Other code does not uses insert function for this.

There are no compiler errors in either of them.

BUT the code with insert function is giving BLANK SCREEN when I run the program where as the other code works well

Please help me figure this out and solve my problem.

What I have tried:

C++
#include <iostream>

using namespace std;

struct node{
int data;
node*next;
};
node*head=NULL;
node* insert_(node*head,int size)
{

    for (int i=0;i<size;i++)>
    {
        node*temp=new node;
        temp->data=i;
        temp->next=head;
        head=temp;
        return head;
        }
}
int main()
{
insert_(head,4);
while(head)
{
    cout << head->data ;
    head=head->next;
}
}

CODE WITHOUT INSERT FUNCTION(which works well)
C++
#include <iostream>

using namespace std;

struct node{
int data;
node*next;
};
node*head=NULL;

int main()
{
for (int i=0;i<5;i++)
    {
        node*temp=new node;
        temp->data=i;
        temp->next=head;
        head=temp;

        }



while(head)
{
    cout << head->data  ;
    head=head->next;
}
}
Posted
Updated 14-Jun-16 6:51am
v3
Comments
CHill60 14-Jun-16 6:36am    
Did you try debugging to see what is going on?

In the insert version you are passing head as parameter using the same name as your global variable. Because it is a function, the local (parameter) variable is used and the content of the global variable is left unchanged.

In the second version the global variable is used and modified.

To get similar behaviour assign the return value of the insert function to your global variable:
head = insert_(head,4);


[EDIT]
And of course the error reported in solution 1 which I did not saw because the code was initially not formatted.
[/EDIT]
 
Share this answer
 
v2
Comments
Member 12566145 14-Jun-16 6:52am    
Thanks for your help.. Finally made the linked list and printed it
I think it is because you have return in for cycle, but i guess it should be out of it.
like this:
C#
for (int i=0;i<size;i++)>
    {
        node*temp=new node;
        temp->data=i;
        temp->next=head;
        head=temp;
        
        }
return head;
 
Share this answer
 
Comments
Member 12566145 14-Jun-16 6:53am    
thanks for you help :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900