Templates in C++ is a tool for generic programming. In general we want to make program that is independent of input type (integer, real, strings etc.).
Here we want to create a List class that in generic in nature and works or all sort of input type like strings , integers, float, double, chars etc.
Here we want to create a List class that in generic in nature and works or all sort of input type like strings , integers, float, double, chars etc.
#include <iostream>
#include <string>
using namespace std;
template <class T> class List;
template <class T>
class Node
{
friend class List<T>;
T val;
Node<T> *link;
public:
Node() {}
Node(T v) : val(v), link(NULL) {}
Node(T v, Node<T> *p) : val(v), link(p) {}
};
template <class T>
class List
{
int size;
Node<T> *head;
public:
List() : size(0) {
head = new Node<T>();
}
void append(T);
void prepend(T);
void insertAt(T, int);
void show() const;
inline int len() { return size; }
};
template <class T>
void List<T>::append(T item)
{
Node<T> *pivot = new Node<T>(item);
if (size == 0) {
head->link = pivot;
}
else {
Node<T> *temp = head;
while (temp->link != NULL) {
temp = temp->link;
}
temp->link = pivot;
}
size++;
}
template <class T>
void List<T>::insertAt(T item, int pos)
{
Node<T> *pivot = new Node<T>(item);
if (pos <= size+1 && pos > 0) {
int i = 0;
Node<T> *temp = head, *prev;
while (i != pos) {
++i;
prev = temp;
temp = temp->link;
}
pivot->link = temp;
prev->link = pivot;
size++;
}
else {
cerr << "Invalid Position '" << pos << "' Sprecified." << endl;
}
}
template <class T>
void List<T>::prepend(T item)
{
Node<T> *pivot = new Node<T>(item);
if (size == 0) {
head->link = pivot;
}
else {
Node<T> *temp = head->link;
head->link = pivot;
pivot->link = temp;
}
size++;
}
template <class T>
void List<T>::show() const
{
Node<T> *tmp = head->link;
cout << "[";
while (tmp != NULL) {
cout << tmp->val << "," << ends;
tmp = tmp->link;
}
cout << "\b\b]" << endl;
}
int main()
{
List<int> a;
a.append(2);
a.append(3);
a.prepend(1);
a.append(5);
a.show();
a.insertAt(-1, 0);
a.insertAt(4, 4);
a.insertAt(6, 6);
a.show();
cout << "Length Of The List Of Integers: " << a.len() << endl;
List<string> b;
b.append("Cat");
b.append("Dog");
b.append("Mouse");
b.append("Bird");
b.show();
cout << "Length Of The List Of Strings: "<< b.len() << endl;
return 0;
}
[1, 2, 3, 5] Invalid Position '0' Sprecified. [1, 2, 3, 4, 5, 6] Length Of The List Of Integers: 6 [Cat, Dog, Mouse, Bird] Length Of The List Of Strings: 4 --------------------------------