Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <iostream>
- #include "stack.h"
- using namespace std;
- stack::stack()
- {
- // this->top=0;
- this->data = (int*)malloc(sizeof(int) * 2);
- if(this->data == NULL)
- {
- cout << "unable to allocate memory" << endl;
- exit(1);
- }
- this->top=-1;
- this->size=2;
- }
- stack::~stack()
- {
- free(this-> data);
- }
- bool stack::isEmpty()
- {
- if(this->top == -1)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- void stack::push(int element)
- {
- int *temp = (int*)malloc(sizeof(int) * this->size * 2);
- if (temp == NULL)
- {
- cout <<"unable to allocate" << endl;
- return;
- }
- int i=0;
- for(i = 0; i<= this ->top; i++)
- {
- temp[i] = this->data[i];
- }
- free(this->data);
- this->data = temp;
- this-> size *=2;
- this-> data[++this->top] = element;
- }
- int stack::pop()
- {
- if(isEmpty())
- {
- cout << "stack is empty" << endl;
- free(this->data);
- exit(-1);
- }
- else
- {
- return this->data[this->top--];
- }
- }
- stack::stack(const stack &s)
- {
- this->data = (int*)malloc(sizeof(int) * s.size);
- if(this->data == NULL)
- {
- printf("unable to allocate memory");
- exit(1);
- }
- this->top=s.top;
- this->size=s.size;
- for(int i = this->top; i>=0;i--)
- {
- this->data[i] = s.data[i];
- }
- }
- stack & stack::operator= (const stack & s)
- {
- if(this->size != s.size)
- {
- this->data = (int*)realloc(this->data, sizeof(int) * (s.size));
- }
- this->top=s.top;
- this->size=s.size;
- for(int i = s.top; i>=0;i--)
- {
- this->data[i] = s.data[i];
- }
- return *this;
- }
- void stack::display()
- {
- for(int i =this->top; i>=0; i--)
- {
- printf(" %d ", this->data[i]);
- }
- printf("\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement