Skip to content

Instantly share code, notes, and snippets.

@jmkim
Created May 4, 2016 10:43
Show Gist options
  • Save jmkim/8d4480c376f64ffc60ad5f311fc1826d to your computer and use it in GitHub Desktop.
Save jmkim/8d4480c376f64ffc60ad5f311fc1826d to your computer and use it in GitHub Desktop.
#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