Hello. I implement the list class. I have a structure:

template<class T> struct object { T object; // сам объект T *nextObject = NULL; } 

And the class itself:

 class Queue { Object *head; public: void push_back(???) { Object obj = new Object; obj->object = ??? } } 

The essence of the question: what parameter to pass to the push_back method?

  • It was a little wrong with the names, the structure is not object, but Object - Alex
  • You must have a Queue template, otherwise - what Object does it contain? Well and further, it is clear that in push_back it is necessary to transfer either T , or const T& . But I would not use an assignment, but a copy constructor. - Harry
  • If you have a type template, then its instance inside the Queue should be template, i.e. Object<нужный_тип> *head; with all that it implies. - αλεχολυτ
  • And yet - if you have such a single-linked list, then you need to keep another pointer to the end of the list - otherwise, going through the entire list every time to add something to the end is too expensive ... - Harry
  • @Harry, yes, thank you, remade it for a template class. To begin with, I want to implement a unidirectional list, and after it works, I will do bidirectional - Alex

1 answer 1

Like that:

 template<typename T> class List { struct Object { T obj; Object* next; Object(const T& t):obj(t),next(nullptr){} }; Object * head = nullptr, * last = nullptr; public: void push_back(const T& t) { Object * obj = new Object(t); if (last) last->next = obj; last = obj; if (head == nullptr) head = obj; } ....... }; 

I think the idea is clear? Further functionality is not a problem to write?

  • Thank you, on the whole, everything is clear, I'll it out further) - Alex
  • Well then good luck :) - Harry