There is an ordinary unidirectional list with the function to add an element to the beginning and display a list:

#include "stdafx.h" #include <iostream> using namespace std; /*template<typename T> */struct Link{ /*T*/int data; Link* next; }; class List{ Link* first; public: List() :first(NULL){} ~List(){ Link *current = first; while (current != NULL){ Link* temp = current; current = current->next; delete temp; } cerr << "Deleted" << endl; } void add(int d){ //добавление в начало Link* newlink = new Link; newlink->data = d; newlink->next = first; first = newlink; } void show(){ Link* current = first; while (current){ cout << current->data << endl; current = current->next; } } }; int _tmain(int argc, _TCHAR* argv[]){ List LS; int n = 3; for (int i = 0; i < n; i++){ LS.add(i); } LS.show(); _gettch(); return 0; } 

How to add a template here? so that you can insert any type of data:

 template<typename T> struct Link{ T data; Link* next; }; 

I know how to do this simply with a CLASS:

 template <class T> class Stack{ enum {MX=5}; T st[MX]; int top; public: Stack(); void push(T ); T pop(); }; 

But I can’t get around this double nesting: I put template<typename T> in front of the class and each method. Changed int d to T d ... Even when creating List LS; (or List<int> LS; ) underlines in red and displays an error.

  • nest struct link inside the list class. - KoVadim
  • Just wondering - are you writing like that? template<typedef T> ? not template<typename T> ? ... :) - Harry
  • @KoVadim helped, thanks. And what about the option via 'Link <T> * current'. Just below rewrote the code. But not completely debugged - Jora Petrov
  • one
    Do not ask new questions by editing old ones, because this makes the answers not relevant. If you have a new question - ask it separately. - Abyx

1 answer 1

There is no double nesting, just if you have the Link template class, then the class containing it must either use only one version (specific) of this Link , or be template template too.

 template<typename T> struct Link{ T* data; Link* next; }; template<typename T> class List{ Link<T>* first; public: List() :first(nullptr){} ~List(){ Link<T> *current = first; while (current != nullptr){ Link<T>* temp = current; current = current->next; delete temp; } cerr << "Deleted" << endl; } // и т.д. в том же ключе }; 
  • corrected, thanks. What to do now? Rewrote the code below - Jora Petrov
  • one
    @JoraPetrov, can you read a book, the simplest one? Link<T>* newlink = new Link<T>; - ixSci