How can we combine in this case two lists into one? If I make u2 = u; Then I will receive only a copy of the first list, but how else can I get the second list of u1? That is, the output I have to get the list: 1 2 3 3

class _List{ private: List* newList; public: _List() { newList = NULL; } void additem(int d); void additem2(); void Prints(); }; void _List::additem(int d){ List* createList = new List; createList -> da = d; createList -> next = NULL; List* x = new List; if (newList != NULL) { x = newList; while ((x->next) != NULL){ x = x->next; } x -> next = createList; }else{ newList = createList; } } void _List::Prints() { List* p = newList; cout <<"Spisok: ="; while (p){ cout<<p->da<<" "; p=p->next; } } int main(int argc, char* argv[]) { _List u; _List u1; _List u2; u.additem(1); u.additem(2); u.additem(3); u1.additem(3); u.Prints(); u1.Prints(); getch(); return 0; } 
  • usually the last item in list 1 p->next = u2 - pavel
  • @pavel There is a link to this element, it is impossible to do so. And how to make a method in class, I can not guess - Kureid

1 answer 1

First, you have a memory leak in the _List::additem function. Replace the desired line with the following.

 List* x; // = new List; 

Secondly, there are 2 ways to combine lists.
The first has already been called. At the end of the first list we write a pointer to the second. The destruction of the second list will lead to errors in the first. I see no difficulties in implementation.
The second way is to copy the second list to the end of the first. To do this, we declare the function void _List::additem(_List &list); and its implementation is very simple:

 void _List::additem(_List &list) { List* x = list.newList; while (x != NULL) { additem(x->da); x = x->next; } } 

Association is as follows:

 _List u; _List u1; _List u2; // Заполнение двух списков u2.additem(u); u2.additem(u1); u2.Prints();