main.cpp:
#include <iostream>
#include "data/stack.h"
using namespace std;
int main()
{
Stack<double> st = Stack<double>();
for (int i=10; i>=0; --i)
{
double t = (double)(i)+0.5;
st.push(t);
}
while (st.length() > 0)
{
cout << st.pop() << endl;
}
return 0;
}
stack.h:
#ifndef STACK_H_
#define STACK_H_
#include <iostream>
template <class Type>
class Node
{
public:
Node<Type>* next;
Type& value;
Node(Type& v, Node<Type>* n) : value(v), next(n) {}
~Node()
{
delete next;
}
};
template <class Type>
class Stack
{
private:
Node<Type>* root;
unsigned int l;
public:
Stack()
{
root = 0;
l = 0;
}
~Stack()
{
delete root;
}
unsigned int length()
{
return l;
}
void push(Type& t)
{
root = new Node<Type>(t, root);
++l;
}
Type& pop()
{
Type& r = root->value;
Node<Type>* t = root;
root = root->next;
t->next = 0;
delete t;
--l;
return r;
}
Type& peek()
{
return root->value;
}
};
#endif
output:
0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5












