Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <assert.h>
- #include <string.h>
- #include "stack2b.h"
- #define STACKSIZE 3
- #define INIT -1
- using namespace std;
- Stack::Stack()
- {
- totalSize = STACKSIZE;
- top = INIT;
- array = (int*)malloc(sizeof(int)*totalSize);
- if(array == NULL)
- {
- printf("Memory not allocated\n");
- abort();
- }
- }
- Stack::Stack(const Stack &obj)
- {
- top = obj.top;
- totalSize = obj.totalSize;
- array = (int*)malloc(sizeof(int) * totalSize);
- // assert(array != NULL);
- for(int i=0; i<obj.totalSize; i++)
- {
- array[i] = obj.array[i];
- }
- }
- Stack& Stack::operator= (const Stack &obj)
- {
- top = obj.top;
- totalSize = obj.totalSize;
- array = (int*)realloc(array, sizeof(int) * totalSize);
- // assert(array != NULL);
- for(int i=0; i<obj.top; i++)
- {
- array[i] = obj.array[i];
- }
- return *this;
- }
- void Stack::copy(const Stack &obj)
- {
- top = obj.top;
- for(int i=0; i<obj.top; i++)
- {
- array[i] = obj.array[i];
- }
- }
- void Stack::push(int element)
- {
- if(top == totalSize - 1)
- {
- totalSize *= 2;
- int *temp = (int*)realloc(array, sizeof(int)*totalSize);
- if(temp == NULL)
- {
- cout<<"Realloc failed"<<endl;
- abort();
- } else {
- array = temp;
- }
- }
- array[++top] = element;
- }
- int Stack::pop()
- {
- if(isEmpty())
- {
- cout<<"Stack is empty"<<endl;
- abort();
- }
- return array[top--];
- }
- bool Stack::isEmpty()
- {
- if(top == -1)
- {
- return true;
- } else {
- return false;
- }
- }
- void Stack::getTotatSize()
- {
- printf("Size of stack is: %d\n", totalSize);
- }
- Stack::~Stack()
- {
- free(array);
- }
- void Stack::display(){
- int i;
- for(i = 0; i <= top; i++)
- cout << array[i]<<endl;
- }
- int Stack::giveTop()
- {
- return array[top];
- }
- #include <iostream>
- #include <string>
- #include <string.h>
- #include "stack2b.h"
- #include "stack2b.cpp"
- #define STACKSIZE 3
- #define DOUBLE_SIZE 2
- #define INITIAL_TOP -1
- using namespace std;
- int main(int argc, char const *argv[])
- {
- Stack s;
- assert(s.isEmpty()==1);
- s.push(1);
- s.push(2);
- s.push(3);
- s.display();
- cout<<endl;
- assert(s.pop()==3);
- s.display();
- cout<<endl;
- Stack s2(s);
- assert(s2 ==s);
- s2.display();
- cout<<endl;
- s.push(3);
- s.push(4);
- //assert(s2.giveTop()==4);
- assert(s2.isEmpty()==0);
- assert(s2.pop()==4);
- s2.display();
- cout<<endl;
- s=s2;
- s2.display();
- cout<<endl;
- s.display();
- return 0;
- }
- #pragma once
- class Stack{
- int totalSize;
- int top;
- int * array;
- public:
- void display();
- void push(int elemennt);
- int pop();
- bool isEmpty();
- int giveTop();
- void getTotatSize();
- void copy(const Stack &obj);
- Stack(const Stack &obj);
- Stack& operator= (const Stack &obj);
- Stack();
- ~Stack();
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement