Your addAfter() function looks quite wonky. I'm not sure it does anything useful.
It should perform these tasks:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
// Find the ith node in l1
Node* p = first;
for(int k=1; k<i && p != NULL; ++k)
p = p->next;
// link l2 into l1 here
if( p != NULL )// still pointing to valid Node
{
l2.last->next = p->next;// rest of l1 follows l2
p->next = l2.first;//l2 follows 1st part of l1
l2.first = l2.last = NULL;// l2 now empty
}
|
Done!
edit: I missed a case. calling L1.addAfter(N, L2) for a list with N nodes means to insert L2 after L1 tail, ie. concatenate L2 to L1.
This code following line 10 above should correct:
1 2
|
if( l2.last->next == NULL )// there is no "rest of" l1 and l1 has a new last node
l1.last = l2.last;
|
edit2: Looking at your code for addAfter() more closely I see a disaster caused by lines 126-128.
since current is never NULL in the for loop, lines 126-128 are executed every iteration of the for loop
Lines 126-128 allocate a new node and insert it in the list after the current node.
In the next iteration current points to the node newly allocated in the last iteration.
Another node is inserted, current doesn't advance through the list. The for loop never ends and the list expands forever following node #i. This is your program "stopping".
edit3: I realize you probably want to copy L2 into L1 (leaving L2 intact), not move it there (leaving L2 empty). This more closely matches what your code is attempting.
Ahem...
Start as before. Find the node to insert after:
1 2 3
|
Node* p = first;
for(int k=1; k<i && p != NULL; ++k)
p = p->next;
|
Then insert new nodes as copies from L2. Your code doesn't advance through L2 at this point:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
if( p != NULL )// still in list
{
const Node* it2 = L2.first;
while( it2 != NULL )
{
Node* newNode = new Node( it2->num );
newNode->next = p->next;
p->next = newNode;
p = newNode;// to insert after next iteration
it2 = it2->next;// next node in L2
}
if( !it2->next == NULL )
tail = it2;// new tail
}
|
I've been testing this on a doubly linked list class of mine, and it's all working there.
Now, you'd think the code for this on a doubly linked list would be more complicated but due to a constructor definition in the node class, it's actually simpler.
From my dnode class:
1 2 3 4 5 6
|
// make all assignments required to splice this node into list
dnode( int X, dnode* Prev, dnode* Next ): x(X), prev(Prev), next(Next)
{
if(prev) prev->next = this;
if(next) next->prev = this;
}
|
So my code in the while loop is:
1 2 3 4 5 6
|
while( it2 )
{
new dnode( it2->x, it, it->next );// I don't even need to catch the returned address!!
it = it->next;
it2 = it2->next;
}
|
My dList class has 2 new functions, addListAfter_move() and addListAfter_copy() now.
Thank you!
edit4: Finally, I've combined approaches for the copy version.
1. Create a copy of L2 in the function.
2. Splice this copy into L1 as in the 1st move approach.