This java code basically implements stack functionality. It can Pop and Push an item in stack with the help of array. The item can only be an integer number and inernally the java program uses arrays to maintain items in stack.

[code=’java’]
/*******************************************************
* MYCPLUS Sample Code – http://www.mycplus.com *
* *
* This code is made available as a service to our *
* visitors and is provided strictly for the *
* purpose of illustration. *
* *
* Please direct all inquiries to saqib at mycplus.com *
*******************************************************/

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; } [/code]

0 Shares
Share
+1
Tweet
Share
Stumble