StackNode.h
#ifndef __STACKNODE_H__ #define __STACKNODE_H__ template <class T> class StackNode { public: T data; StackNode<T>* nextNode; }; #endif
StackList.h
#ifndef __STACKLIST_H__ #define __STACKLIST_H__ #include "StackNode.h" template <class T> class StackList { private: StackNode<T>* top; public: StackList(); ~StackList(); void Push(T _data); T Pop(); T getTop(); bool isEmpty(); }; #endif
StackList.cpp
#include "StackList.h" #include <iostream> #include <string> using namespace std; template <class T> StackList<T>::StackList() { top = nullptr; } template <class T> StackList<T>::~StackList() { while(top != nullptr) { StackNode<T>* deleteNode = new StackNode<T>; deleteNode = top; top = top->nextNode; delete deleteNode; } } template <class T> void StackList<T>::Push(T _data) { StackNode<T>* newNode = new StackNode<T>; newNode->data = _data; newNode->nextNode = top; top = newNode; } template <class T> T StackList<T>::Pop() { T tempData = top->data; StackNode<T>* tempNode = new StackNode<T>; tempNode = top; top = top->nextNode; delete tempNode; return tempData; } template <class T> T StackList<T>::getTop() { return top->data; } template <class T> bool StackList<T>::isEmpty() { if(top == nullptr) return true; return false; }
LinkedStack.cpp
#include <iostream> #include <string> #include "StackList.h" #include "StackList.cpp" using namespace std; int main() { StackList<string>* stack = new StackList<string>; cout << stack->isEmpty() << endl; stack->Push("test0"); stack->Push("test1"); stack->Pop(); cout << stack->getTop() << endl; return 0; }