Question

How do I convert the following pseudo code into an array instead of a stack. The algorithm is intended to construct a digraph given a certain input:

  1. Scan the formula from right to left calling symbols on a stack until 2 consecutive node symbols appear on top.
  2. Pop off these 2 node symbols and the '*' just below them on the stack. Draw an edge from the first symbol to the second.
  3. Push the first symbol on the stack.
  4. Continue steps 1-3 until the formula is processed.

Here is a sample input and output:

Input:

***ABCD

Output:

*AB, *AC, *AD

'*' represents an edge

All inputs will be done using a scanner.

Was it helpful?

Solution 2

You have basically to perform operations on the array using the FIFO propriety.

public ArrayStack( )
{
    theArray = new String[InitialSize];
    topOfStack = -1;
}

Every time you add an element to your array (push) you do topOfStack++; and insert the element on the "topOfStack" position of the array. By doing topOfStack++ you are keeping track of the array position that became the new top of the stack.

When you do pop you must check if the array is not empty, return the element on array[topOfStack] and do topOfStack--;. Because the top is now the previous position on the array.

If you need more space for your array because the stack is full (topOfStack == InitialSize) you have to create another array with more space, for example :

private void doubleArray( )
{
        String [] newArray = new String[ theArray.length * 2 ];
        for( int i = 0; i < theArray.length; i++ )
            newArray[ i ] = theArray[ i ];
        theArray = newArray;
 }

For stating, this is roughly what you need to look for, naturally, there are many more details to look into. Nevertheless, try it out yourself, and when you have doubts look for resources such as this.

OTHER TIPS

A stack of limited size can be modeled using an array and an index for the "stack index".

Start the stack index at -1. On push operations, increment the stack index, and store the value at the corresponding index of the array. On pop operations, use the value at the stack index, and decrement the index after fetching the value. To access the top of the stack, read the item at the stack index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top