954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

linked list pointer problem

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.

flash121
Light Poster
49 posts since Jan 2008
Reputation Points: 10
Solved Threads: 0
 

>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;
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Thanks, that worked nicely.

flash121
Light Poster
49 posts since Jan 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You