Templates For Java - Epaperpress Page 2

ADVERTISEMENT

With Templates
////////////
// List.h //
////////////
template<class T>
// template<typename T> is also legal
struct Node {
Node<T> *next;
T value;
};
template<class T>
class List {
public:
List();
~List();
void push_front(T x);
private:
Node<T> *head;
};
template<class T>
List<T>::List() {
head = NULL;
}
template<class T>
List<T>::~List() {
Node<T> *p = head;
while (p) {
Node<T> *next = p->next;
delete p;
p = next;
}
}
template<class T>
void List<T>::push_front(T x) {
Node<T> *p = new Node<T>;
p->value = x;
p->next = head;
head = p;
}
//////////////
// main.cpp //
//////////////
#include "List.h"
int main() {
List<int> x;
x.push_front(5);
x.push_front(3);
List<double> y;
y.push_front(3.14);
return 0;
}

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 3