I'm learning linked lists in C++.

In an exercise I have to duplicate H time a give item.

So I thought in this method:

void duplicaNodo(int item, int &H, Pnodo &L){
    //duplica un nodo H volte, scorrendo tutta la lista
    Pnodo Temp, Temp2;
    if(L!=NULL){
        if(L->info==item){
            for(int i=0; i<H; i++){
                creaNodo(item, Temp);
                Temp->next=L->next;
                L->next=Temp;
            }
            Temp2=Temp->next;                    //Delete this
            duplicaNodo(item, H, Temp2->next);   //to stop at first occurrence
        } else {
            duplicaNodo(item, H, L->next);
        }
    }
}

Can you give some suggestions or I did it right?

I wouldn't use recursion for this, but that doesn't mean your way is wrong if it does the job.

Yes it does the job. Anyway why you would not use the recursion?

this will not do the job please try it :
recheck:
1-this will add only single item not H
2-and if 2 items are in row will doplicate the first only
3-and will crash if inal item is match

No, it will not crash.

Just tried it right now.

1. There is a for
2. That's why I added this:

Temp2=Temp->next;                    //Delete this
duplicaNodo(item, H, Temp2->next);   //to stop at first occurrence

3. Will not crash anyway.

For each issue rechecked
1-sorry you were right i thought it was nodo not Pnodo( Pnodo Temp)
2- try this

Pnodo pRoot;
		creaNodo(0,&pRoot);
		Pnodo pIntermediate;
		creaNodo(0,&pIntermediate);
		Pnodo pLast;
		creaNodo(1,&pLast);

		pRoot->next=pIntermediate;
		pIntermediate->next=pLast;
		cout<<"Print Pefore dup.\r\n";
		print(*pRoot);
		int count=1;
		duplicaNodo(0,count,pRoot);
		cout<<"Print After dup. 1\r\n";
		print(*pRoot);

you will got
0 0 1
then
0 0 0 1
not
0 0 0 0 1
3-try this

Pnodo pRoot;
		creaNodo(0,&pRoot);

		cout<<"Print Pefore dup.\r\n";
		print(*pRoot);
		int count=1;
		duplicaNodo(0,count,pRoot);
		cout<<"Print After dup. 1\r\n";
		print(*pRoot);
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.