LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   c++ doubly linked lists (https://www.linuxquestions.org/questions/programming-9/c-doubly-linked-lists-150497/)

durden2.0 02-25-2004 05:38 PM

c++ doubly linked lists
 
Ok I have one little bug and it is driving me crazy. I think I might have been just working with doubly linked lists for too many hours straight. Here is my problem, I am wanting to add to lists together. For example, I want to take list2 and put it on the end of list1 so that all of list2 is moved and put into list1, on to the back of list1 that is. Both lists are doubly linked lists, here is a little bit of the code, thanks for the help.


if(list2->next != NULL) // check to make sure there is something
{ // worth adding to list1
list1->next = list2;
list2->prev = list1;
}

I am sure it is obvious so someone out there, thanks for the help guys.

xviddivxoggmp3 02-25-2004 05:47 PM

are you using two instansiations of the same object, or did you hard code 2 seperate lists.

The implimentation will differ a little, but both will consist of connecting the pointers you use for head and tail.

kev82 02-25-2004 05:48 PM

well that code doesnt tell me much because i dont know what list1 and list2 are. im gonna assume that list1 is the first element of the first list and list2 is the first element of the second list. in this case what we want to do is find the last element of the first list and put the second one after it so how about.

Code:

list_type *l=list1;
while(l->next != NULL) l=l->next;
l->next=list2;
list2->prev=l;

i cant be more specific unless you show your code and give me a better description of the problem than 'one little bug'

also c++ has a wide range of containers in the stl including std::list you ought to think about using one of these instead unless you are coding a linked list just for understanding.

durden2.0 02-25-2004 05:50 PM

sorry I should have made more sense. Ok here goes, list1 is a pointer to the end of the first list. List2 is a pointer to the first item in list2, and yes it is two seperate lists. The problem I have is a sorting algorithm and after I sort the two lists, I keep adding elements from list2 to list1 and then when it is done I want to add all the remaining elements of list2 to the end of list1. I hope that helps more, sorry about that.

xviddivxoggmp3 02-25-2004 05:56 PM

to have a smaller and cleaner program i would use 2 instansiations of one list object.

but for 2 seperate lists.
I would use the prior suggestion
i do not mean to over simplify, but this should work.
this creates list 3 and kills list 2


All times are GMT -5. The time now is 04:56 AM.