Growable array based stack | CPP Program to implement growable array based stack using tight strategy ; constant amount at which stack is increased ; top of the stack ; length of stack ; function to create new stack ; allocate memory for new stack ; copying the content of old stack ; re - sizing the length ; function to push new element ; if stack is full , create new one ; insert element at top of the stack ; function to pop an element ; function to display ; if top is - 1 , that means stack is empty ; Driver Code ; creating initial stack ; pushing element to top of stack ; pushing more element when stack is full ; pushing more element so that stack can grow
#include <iostream> NEW_LINE using namespace std ; #define BOUND  4 NEW_LINE int top = -1 ; int length = 0 ; int * create_new ( int * a ) { int * new_a = new int [ length + BOUND ] ; for ( int i = 0 ; i < length ; i ++ ) new_a [ i ] = a [ i ] ; length += BOUND ; return new_a ; } int * push ( int * a , int element ) { if ( top == length - 1 ) a = create_new ( a ) ; a [ ++ top ] = element ; return a ; } void pop ( int * a ) { top -- ; } void display ( int * a ) { if ( top == -1 ) cout << " Stack ▁ is ▁ Empty " << endl ; else { cout << " Stack : ▁ " ; for ( int i = 0 ; i <= top ; i ++ ) cout << a [ i ] << " ▁ " ; cout << endl ; } } int main ( ) { int * a = create_new ( a ) ; a = push ( a , 1 ) ; a = push ( a , 2 ) ; a = push ( a , 3 ) ; a = push ( a , 4 ) ; display ( a ) ; a = push ( a , 5 ) ; a = push ( a , 6 ) ; display ( a ) ; a = push ( a , 7 ) ; a = push ( a , 8 ) ; display ( a ) ; a = push ( a , 9 ) ; display ( a ) ; return 0 ; }