Skip to content

Instantly share code, notes, and snippets.

@reterVision
Created January 9, 2014 15:45
Show Gist options
  • Save reterVision/c89c48820e315b33bf50 to your computer and use it in GitHub Desktop.
Save reterVision/c89c48820e315b33bf50 to your computer and use it in GitHub Desktop.
Stack
#include <iostream>
using namespace std;
class Stack
{
public:
Stack(int size);
~Stack();
bool push(int value);
int pop();
bool is_full();
bool is_empty();
void print();
protected:
int* container;
int size;
int count;
};
Stack::Stack(int size)
{
this->container = new int[size];
this->size = size;
this->count = 0;
}
Stack::~Stack()
{
if (this->container != NULL)
delete this->container;
this->size = 0;
this->count = 0;
}
bool Stack::push(int value)
{
if (this->is_full())
{
cout << "Stack overflow!" << endl;
return false;
}
this->container[count++] = value;
return true;
}
int Stack::pop()
{
if (this->is_empty())
{
cout << "Stack lower flow!" << endl;
return -1;
}
int result = this->container[--count];
return result;
}
bool Stack::is_full()
{
return this->size == this->count;
}
bool Stack::is_empty()
{
return this->count == 0;
}
void Stack::print()
{
for (int i=0; i<count; i++)
cout << this->container[i] << endl;
}
int main(int argc, char* argv[])
{
Stack stack(10);
stack.pop();
for (int i=0; i<11; i++)
stack.push(i);
stack.print();
cout << "Pop" << endl;
stack.pop();
stack.print();
cout << "Pop" << endl;
stack.pop();
stack.print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment