Skip to content

Instantly share code, notes, and snippets.

@barthap
Last active January 27, 2019 12:19
Show Gist options
  • Save barthap/62ba90a5e5b5526a4f5a9543af223f81 to your computer and use it in GitHub Desktop.
Save barthap/62ba90a5e5b5526a4f5a9543af223f81 to your computer and use it in GitHub Desktop.
Simplest pointer-based C++ stack definition
#include <iostream>
#include <stdexcept>
template <typename T>
class Stack
{
public:
void push(T elem)
{
auto n = new Node;
n->elem = elem;
n->prev = last;
last = n;
_size++;
}
T& peek()
{
if(empty())
throw std::underflow_error("Cannot peek empty stack!");
return last->elem;
}
T pop()
{
if(empty())
throw std::underflow_error("Cannot pop empty stack!");
auto n = this->last;
this->last = n->prev;
auto el = n->elem;
_size--;
delete n;
return el;
}
const int size() const { return _size; }
const bool empty() const { return _size == 0; }
private:
struct Node
{
T elem;
Node* prev;
};
Node* last = nullptr;
int _size = 0;
};
int main() {
Stack<int> stack;
std::cout << "Stack is empty " << stack.empty() << std::endl;
stack.push(1);
stack.push(2);
std::cout << "Stack size " << stack.size() << std::endl;
std::cout << "Pop: " << stack.pop() << ", peek " << stack.peek() << ", pop: " << stack.pop() << std::endl;
std::cout << "Size: " << stack.size() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment