Greetings,

I'm trying to write a function which gets two pointers as parameters. The first one "points" to the start of the first linked list, the second one is currently on null, but it will later serve as a pointer to the start of another linked list. The function is supposed to loop through the first list and "copy" all number which are on an odd "index" to a new linked list (the pointer i mentioned earlier will point to the start of this one).

Here's my code:

void create(node* start1, node*& start2){
       int i=1;
       node* temp=start1;
       while(temp!=NULL){
                    if(i%2!=0){
                             node* temp1=new node;
                             temp1=temp;
                             temp1->next=start2;
                             start2=temp1;
                   }
                   i++;
                   temp=temp->next; //here's the line where temp starts to point to null
       }
}

While everything seems fine (at least to me) i got a problem. When the program enters the first itteration of the while loop and inserts the number from the first list to the second, the temp pointer redirects itself to null, which stops the loop.

Any help will be much appriciated.

Recommended Answers

All 2 Replies

>temp1=temp;
>temp1->next=start2;
You say start2 is a null pointer, right? Well when you assign temp to temp1, you're aliasing temp, not copying the data at that address. So when you set temp1->next to null, temp->next is also set to null implicitly.

You probably want something more like this:

temp1->data=temp->data;
temp1->next=start2;

Thanks, that worked nicely.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.