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.
template<typedef T>? nottemplate<typename T>? ... :) - Harry