Skip to content

Instantly share code, notes, and snippets.

@nezarfadle
Last active May 7, 2020 23:03
Show Gist options
  • Save nezarfadle/83702081ed95558c86f2825056e822cf to your computer and use it in GitHub Desktop.
Save nezarfadle/83702081ed95558c86f2825056e822cf to your computer and use it in GitHub Desktop.
#include <iostream>
#include "assert.h"
#include <exception>

using namespace std;

class EmptyStackException : public std::exception {};
class FullStackException : public std::exception {};
template<class T, int max>
class Stack
{

private:
    
    T list[ max ];
    int top = -1;
    
public:

    Stack& push( T data )
    {
        if( top >= max - 1 ) throw FullStackException();
        list[ ++top ] = data;    
        return *this;
    }
    
    T pop()
    {
        if( top < 0 ) throw EmptyStackException();
        return list[ top-- ];   
    }
    
    int size()
    {
        return top + 1;
    }
    
    Stack& fill( int start, int end, T data )
    {
        for( int i = start; i <= end; i++ )
            push( data );
        
        return *this;
    }
    
    bool isEmpty()
    {
        return top < 0;
    }
    
    bool isNotEmpty()
    {
        return !isEmpty();
    }
    
};

int main()
{
    
    Stack<int, 10> s;
    s.push( 100 )           
     .push( 300 );
    
    assert( s.isNotEmpty() );
    assert( 300 == s.pop() );
    assert( 100 == s.pop() );
    
    try
    {
        assert( s.isEmpty() );
        assert( s.pop() );
        assert( false );
        
    }
    catch(EmptyStackException e) { assert( true ); }
    catch(...)                   { assert( false ); }
    
    
    try
    {
        s.fill( 1, 10, 1 );    
        assert( 10 == s.size() );
        s.push( 200 );
        assert( false );
    }
    catch(FullStackException e) { assert( true ); }
    catch(...)                  { assert( false ); }
    
    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment