Created
May 4, 2016 10:43
-
-
Save jmkim/8d4480c376f64ffc60ad5f311fc1826d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef ALGORITHM_ADT_STACK_H_ | |
#define ALGORITHM_ADT_STACK_H_ 1 | |
namespace algorithm | |
{ | |
namespace adt | |
{ | |
template<class Element> | |
class Stack | |
{ | |
private: | |
struct Node | |
{ | |
Element element; | |
Node* next; | |
Node(const Element& element) | |
: element(element), next(nullptr) | |
{ } | |
}; | |
Node* top_; | |
int size_; | |
static | |
Node* | |
CreateNode(const Element& element) | |
{ return new Node(element); } | |
static | |
void | |
DestroyNode(Node* node) | |
{ if(node != nullptr) delete node; } | |
public: | |
Stack(void) | |
: top_(nullptr), size_(0) | |
{ } | |
~Stack(void) | |
{ while(! empty()) pop(); } | |
/* element access */ | |
Element& | |
peek(void) | |
{ return top_->element; } | |
/* capacity */ | |
inline bool | |
empty(void) const | |
{ return top_ == nullptr; } | |
inline int | |
size(void) const | |
{ return size_; } | |
/* modifiers */ | |
void | |
push(const Element& element) | |
{ | |
Node* node = CreateNode(element); | |
if(! empty()) | |
node->next = top_; | |
top_ = node; | |
++size_; | |
} | |
void | |
pop(void) | |
{ | |
if(! empty()) | |
{ | |
Node* node = top_; | |
top_ = node->next; | |
--size_; | |
DestroyNode(node); | |
} | |
} | |
}; | |
} /* ns:adt */ | |
} /* ns:algorithm */ | |
#endif /* ! ALGORITHM_ADT_STACK_H_ */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment