I'd like some feedback for the code I wrote. I haven't programmed in C++ for two years.
#include <string>
#pragma once
template <class T>
class StackLinkedList
{
public:
StackLinkedList() : m_List(nullptr), m_Size(0) {}
~StackLinkedList();
void push(const T& val);
void pop();
T& top();
const T& top() const;
size_t size() const;
bool empty() const;
private:
struct Node;
Node *m_List;
size_t m_Size;
};
template <class T>
struct StackLinkedList<T>::Node
{
T m_Val;
Node* m_Next;
Node(const T& val, Node* nextPtr) : m_Val(val), m_Next(nextPtr) {}
};
template<class T>
StackLinkedList<T>::~StackLinkedList()
{
typename Node* nextNodePtr;
for (typename Node* curNodePtr = m_List; curNodePtr != nullptr; )
{
nextNodePtr = curNodePtr->m_Next;
delete curNodePtr;
curNodePtr = nextNodePtr;
}
}
template<class T>
void StackLinkedList<T>::push(const T& val)
{
typename Node* newNode = new Node(val, m_List);
m_List = newNode;
m_Size++;
}
template<class T>
void StackLinkedList<T>::pop()
{
if (m_List != nullptr)
{
typename Node* curNodePtr = m_List;
m_List = m_List->m_Next;
delete curNodePtr;
m_Size--;
}
}
template<class T>
T& StackLinkedList<T>::top()
{
if (empty())
{
throw new std::string("Stack is empty");
}
return m_List->m_Val;
}
template<class T>
const T& StackLinkedList<T>::top() const
{
if (empty())
{
throw new std::string("Stack is empty")
}
return m_List->m_Val;
}
template<class T>
size_t StackLinkedList<T>::size() const
{
return m_Size;
}
template<class T>
bool StackLinkedList<T>::empty() const
{
return m_Size == 0;
}