Growable array based stack | Java 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
class GFG { static final int BOUND = 4 ; static int top = - 1 ; static int length = 0 ; static 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 ; } static int [ ] push ( int [ ] a , int element ) { if ( top == length - 1 ) a = create_new ( a ) ; a [ ++ top ] = element ; return a ; } static void pop ( int [ ] a ) { top -- ; } static void display ( int [ ] a ) { if ( top == - 1 ) System . out . println ( " Stack ▁ is ▁ Empty " ) ; else { System . out . print ( " Stack : ▁ " ) ; for ( int i = 0 ; i <= top ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String args [ ] ) { int [ ] a = create_new ( new int [ length + BOUND ] ) ; 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 ) ; } }