This java code implements stack functionality by using arrays. It can Pop and Push an item in stack with the help of array. The item can only be an integer number and internally the java program uses arrays to maintain items in stack.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import java.awt.event.*; import java.awt.*; import javax.swing.*; public class ArrayStack implements Stack { // Construct the stack. public ArrayStack( ) { theArray = (AnyType []) new Object[ DEFAULT_CAPACITY ]; topOfStack = -1; } public boolean isEmpty( ) { return topOfStack == -1; } public void makeEmpty( ) { topOfStack = -1; } public AnyType top( ) { if( isEmpty( ) ) throw new UnderflowException( "ArrayStack top" ); return theArray[ topOfStack ]; } public void pop( ) { if( isEmpty( ) ) throw new UnderflowException( "ArrayStack pop" ); topOfStack--; } public AnyType topAndPop( ) { if( isEmpty( ) ) throw new UnderflowException( "ArrayStack topAndPop" ); return theArray[ topOfStack-- ]; } // Insert a new item into the stack. public void push( AnyType x ) { if( topOfStack + 1 == theArray.length ) doubleArray( ); theArray[ ++topOfStack ] = x; } // Internal method to extend theArray. private void doubleArray( ) { AnyType [ ] newArray; newArray = (AnyType []) new Object[ theArray.length * 2 ]; for( int i = 0; i < theArray.length; i++ ) newArray[ i ] = theArray[ i ]; theArray = newArray; } private AnyType [ ] theArray; private int topOfStack; private static final int DEFAULT_CAPACITY = 10; } |