Guidance needed in Concatenation of LinkedList program

I need to create a function that takes two lists as parameters and creates a new list by concatenating the first list with the second list. So far I have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

#ifndef H_LINKEDLIST
#define H_LINKEDLIST

#include <iostream>
using namespace std;

struct ListNode
{
	double data;
	ListNode *next;
};

struct LinkedList
{
	ListNode *head;
	int size;
};


LinkedList createList()
{
	LinkedList list;
	list.head = NULL;
	list.size=0;
	return list;
}


LinkedList catList(LinkedList &list1, LinkedList &list2)
{
	LinkedList newList;
	newList = createList( );
	newList.head = list1.head;
	list1.head ->
	ListNode *head;
	head = NULL;
}



I am having trouble with my pointers, and am also unsure if I require a loop, or how I would even go about creating one that combine two lists together. Much help appreciated, and yes this is a .h

Thank you.



Last edited on
Please? Anyone?
It depends. Do you want your old lists to remain the same? If so, that's going to be difficult, as the Linked part happens inside the elements, not inside the Lists.

If you don't need the old lists (which should be the case in most applications), you only need these steps:
1) newlist.head = oldlist1.head; (Set starting point of new list on first point of an old list)
2) oldlist1.last->next = oldlist2.head; (Link last of oldlist1 to first of oldlist2)
3) Delete oldlist1 and oldlist2.

The easiest (best?) way to do this is through a constructor that accepts two LinkedList objects as parameters. The way you did it is also an option, but I recommend against it.

For step 3, do mind possible side-effects caused by your deconstructors. If your linked list takes care of its own nodes through recursive deletion, you'll also be deleting the content of your new list.
After the statement executes list1 and list 2 should be empty

So so far I have
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

LinkedList catList(LinkedList &list1, LinkedList &list2)
{
	ListNode *nodePtr, *nextNode, *firstNode;
	

	LinkedList newList1;
	LinkedList newList2;
	newList1 = createList();
	newList2 = createList();
	newList1.head = newList1.head;

	newList1.last->next = newList2.head;
	ListNode *head;


	head = NULL;
	
}




still could use a lot of help with my pointers though.
Last edited on
Topic archived. No new replies allowed.