Could anyone provide any constructive criticism? I'm trying to get a jump on data structures before classes start.
One thing is that I should add a copy constructor and assignment operator. Changes made: got rid of using namespace std
.
As the code allows users to specify a cap, if they wish, for their stack any ideas of how I could signal that that particular stack is full? Currently I'm outputting a message from within the method but I don't like it when method handle output. What about a method that returns whether the stack is full?
#include <iostream>
using namespace std; // TESTING
template <typename T>
class Stack
{
public:
Stack()
: head(nullptr), capacity(0), currSize(0), sized(false)
{}
Stack(int cap)
: head(nullptr), capacity(cap), currSize(0), sized(true)
{}
~Stack();
void push(T val);
void pop();
bool isEmpty() const { return head == nullptr; }
int size() const;
T top() const;
private:
template <typename T>
struct StackNode
{
StackNode()
:data(0), next(nullptr)
{}
StackNode(T val, StackNode *ptr = nullptr)
:data(val), next(ptr)
{}
T data;
StackNode *next;
};
StackNode<T> *head;
int capacity;
int currSize;
const bool sized;
};
template <typename T>
Stack<T>::~Stack()
{
while (head != nullptr)
{
StackNode<T> *tmp = head->next;
delete head;
head = tmp;
}
}
template <typename T>
void Stack<T>::push(T val)
{
if (sized == false || currSize != capacity)
{
head = new StackNode<T>(val, head);
++currSize;
}
else cout << "stack full" << endl; //delete
}
template <typename T>
void Stack<T>::pop()
{
if (head != nullptr)
{
StackNode<T> *tmp = head;
head = head->next;
delete tmp;
--currSize;
}
}
template <typename T>
int Stack<T>::size() const
{
return currSize;
}
template <typename T>
T Stack<T>::top() const
{
if (head != nullptr)
{
return head->data;
}
else return NULL;
}
int main()
{
Stack<char> myStack(3);
cout << "is isEmpty: " << myStack.isEmpty() << endl;
cout << "push: "; myStack.push('H'); cout << myStack.top() << endl;
cout << "push: "; myStack.push('G'); cout << myStack.top() << endl;
cout << "push: "; myStack.push('B'); cout << myStack.top() << endl;
cout << "push: "; myStack.push('D'); cout << myStack.top() << endl;
myStack.pop();
cout << "push: "; myStack.push('D'); cout << myStack.top() << endl;
cout << "Size: " << myStack.size() << endl;
cout << "Destroyed" << endl; myStack.~Stack();
cout << endl << endl;
system("pause"); // TESTING
return 0;
}
using namespace std;
with// TESTING
? \$\endgroup\$