This is my first template implementation. I'm trying to learn C++ and Algorithms. Any constructive criticism on code quality, readability is welcome. Everyone has their own style, but there are certain rules which all good programmers should follow. Kindly remark as to if I have followed those and what rules are missing.
#include <iostream>
#include <new>
using std::cout; using std::cin; using std::endl;
using std::nothrow; using std::size_t;
template<typename T> class Stack {
public:
// constructor for class
Stack() { count = 0;
last = NULL; }
// destructor for class
~Stack() { if (count > 0) Clr(); }
// push item at last of stack
void Push(T item);
// pop item from last of stack
T Pop();
// get size of stack
size_t Size();
void Clr(); // delete all the elements
// print all the elements
void Print();
private:
// the stack will store elements in the form of a linked list
struct Node {
T value;
Node* next;
};
Node* last; // last points to the last item of the stack
size_t count; // number of elements in stack
};
/*
Check for memory allocation first. If memory allocated, then Push element in
the stack.
*/
template<typename T> void Stack<T>::Push(T item) {
Node* node = new (nothrow) Node;
if (node == NULL) {
cout << "Memory allocation failed " << endl;
return;
} else {
node->value = item;
if (count == 0) {
node->next = NULL;
last = node;
++count;
} else {
node->next = last;
last = node;
++count;
}
}
}
/*
Delete the elements
*/
template<typename T> void Stack<T>::Clr() {
Node* node = last;
while (count != 0) {
Node* tempnode = node;
node = node->next;
delete tempnode;
--count;
}
}
/*
Pop the last element of the stack and return it
*/
template<typename T> T Stack<T>::Pop() {
if (count == 0) {
cout << "No element to delete" << endl;
return (T)0;
} else {
Node* node = last;
T tempval = node->value;
last = node->next;
delete(node);
--count;
return tempval;
}
}
/*
Print all the elements
*/
template<typename T> void Stack<T>::Print() {
if (count == 0) {
cout << "No elements to print" << endl;
return;
} else {
cout << "Printing from top of the Stack to Bottom" << endl;
Node* node = last;
while (node != NULL) {
cout << node->value << "->";
node = node->next;
}
cout << endl;
}
}
/*
Get the size of the Stack
*/
template<typename T> size_t Stack<T>::Size() {
return count;
}
/*
Main function
*/
int main() {
Stack<int> s;
s.Push(12);
s.Push(10);
s.Push(23);
s.Push(34);
cout << "The value Popped from the Stack: " << s.Pop() << endl;
s.Print();
return 0;
}