c++ append

Trying to get this function to work. It's supposed to append list2 to list1 and then removes all the nodes of list2.


void intSLList:: append( intsLList & l2)
{
intSLLNode *temp;
temp = head;
while (head!=0)
{
addToTail (head->info);

}
delete tmp;
}


That is the idea I had, but obviously isn't working because of so many attempts at wrong conversions.
My thought was to make a tmp pointer that will traverse the second list, and use the addToTail function (already defined) to get the info from the tmp pointer to the addtoTail function.

Is that too cumbersome?
We don't know much about intSLList and intSLLNode. Class definitions, please.

Is this how append() should work?
1
2
3
4
5
6
7
8
9
10
11
12
intSLList foo;
intSLList bar;

// add nodes to foo and bar

size_t f = foo.size(); // or whatever counts the nodes of a list
size_t b = bar.size();

foo.append( bar ); // move nodes of bar into tail of foo

assert( f + b == foo.size() );
assert( 0 == bar.size() );
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class IntSLLNode {
public:
	IntSLLNode() {
		next = 0;
	}
	IntSLLNode(int el, IntSLLNode *ptr = 0) {
		info = el; next = ptr;
	}
	int info;
	IntSLLNode *next;
};

class IntSLList {
public:
	IntSLList() {
		head = tail = 0;
	}
	~IntSLList();

	int isEmpty() {
		return head == 0;
	}
intSLList is supposed to be to create the lists and intSLLNode is for creating nodes.
I need to append list 2 to list 1 and then empty out list 2.
update:::


got this far- I'm trying another approach- I'm trying to link the tail-> next to the head of the second list.
1
2
3
4
5
6
void IntSLList::appendList(IntSLList & b)
{
	IntSLLNode *temp;
	for (temp = head; temp != 0; temp = temp->next);

}
I need to append list 2 to list 1 and then empty out list 2.

That sounds like
1
2
addToTail(l2.head);
l2.head = nullptr;

Make sure that addToTail() is prepared to add a whole list and not just a single node. What I Really mean is that it must adjust the tail pointer to the end of the whole list.

By the way, it's very common to forget to update the tail pointer when writing list code. Every place where you can update head, there is probably a case where you must update tail also.
Topic archived. No new replies allowed.