views:

674

answers:

7

Hi, I have been given list L1, L2. L1 contains 1,2,3 and L2 contains 4,5,6. how do i copy the contents from L2 to the end of L1 so in the end L1 contains 1,2,3,4,5,6. any suggestions?

+1  A: 

If it's a linked list then each node in the list should have a pointer to the next item in the list. The last node in the list should point to null (or some other way of indicating you're at the end of the list). To copy the contents of L2 to the end of L1, just set the next node pointer of the LAST item of L1 to the FIRST item of L2.

TLiebe
+3  A: 

Not knowing any more about the actual implementation I would say do this:

L1.tail = L2.head

This will link the two list together, You can now throw away the reference to L2.

Lukasz
+1  A: 

Since this is a homework question, I can't give you actual code. But this is an easy problem to work out.

Basically, you just want to append the contents of L2 to the end of L1. As you know, each linked list has a head pointer and a tail pointer. When you append to a list, it means attaching a new node to the tail pointer, then moving the tail pointer forward. So you just need to append the head pointer of L2 to the tail pointer of L1, and move the tail pointer of L1 to the end of the list.

Also, don't forget to update the size of the list, if your list class has an internal size variable to count the number of elements.

Charles Salvia
A: 

What's going to happen to L2 after this? You almost definitely don't want to just change L1.tail to point to L2.head if L2 is going to be used and changed later in the program.

Why not just loop from head to tail of L2 and push the values into L1? (If you're wanting specific implementation details you'll need to tell us which Linked List you're using, or post the code to yours if you wrote it).

Afcrowe
+1  A: 

You commented that this isn't homework, even though it's tagged as homework. I'll take your word for it.

Using the C++ STL list, all you need is the insert method and some iterators.

list<int> L1;
list<int> L2;

// let's just assume that L1 and L2 are initialized in the manner you described

// after this, L1 will contain 1,2,3,4,5,6
L1.insert(L1.end(), L2.begin(), L2.end());
csj
A: 

`***



***`

ffgfgf
A: 

check out http://www.leanrcs.net

james