0
votes

hello everyone so i wanna write a code to do the following: java method that will take two sorted stacks A and B (min on top), and return one stack D that is sorted (min on top). You are allowed to use only the stack operations such as pop, push, isEmpty and peek. Example: suppose A={(top)1,4,7,9} and B={(top)2,3,6}, then the function will return a new stack D= {(top) 1,2,3,4,6,7,9}

but i it didn't work for me :( here's the code and i'm ready for any suggestion

 public static Stack myStack ( Stack A , Stack B) {
Stack D = new Stack();
while(!A.isEmpty()&&!B.isEmpty())
{
    if (A.top>B.top){

        A.pop();
        D.push(A.pop());
    } else {

        B.pop();
        D.push(B.pop());
    } 
}
return D;
}

Here's the stack class:

public class Stack {
    private Object [ ] theArray;
    public int top;

    private static final int DEFAULT_CAPACITY = 10;

    //constructor
    public Stack( ) {
        theArray = new Object[ DEFAULT_CAPACITY ];
        top = -1;
    }

    public boolean isEmpty( ) {
        return top == -1;
    }

    public void makeEmpty( ) {
        top = -1;
    }

    public Object peek( ) {
        if( isEmpty( ) )
            throw new UnderflowException( "Stack is Empty" );
        return theArray[ top ];
    }

   public Object pop( ) {
        if( isEmpty( ) )
            throw new UnderflowException( "Stack is Empty" );
        return theArray[ top-- ];
    }

   public void push( Object x ) {
        if( top + 1 == theArray.length )
            doubleArray( );
        theArray[ ++top ] = x;
    }
       private void doubleArray( ) {
        Object [ ] newArray;

        newArray = new Object[ theArray.length * 2 ];
        for( int i = 0; i < theArray.length; i++ )
            newArray[ i ] = theArray[ i ];
        theArray = newArray;
    }

    public class UnderflowException extends RuntimeException {
        public UnderflowException( String message ) {
                super( message );
       }

So what should I do?

1
Think about the algorithm before you code it. You have to get the largest number (in your example 9) on the bottom of Stack D. How do find the largest value amongst 2 stacks (only using the two stacks A and B). Once you figure that out, just continue the process. Give it another go and comment me using @Michael Markidis if you need help. - Michael Markidis

1 Answers

-1
votes

public Stack MyStack (Stack A, Stack B) {

Stack C = new Stack();

while (!A.empty() && !B.empty()) {

if ( (A.top()).compareTo(B.top() )<0 )

C.push(A.pop());

else

C.push(B.pop()); }

if (A.empty())

while ( !B.empty() ) C.push(B.pop());

if (B.empty())

Stack D = new Stack();

while ( !A.empty() ) C.push(A.pop());

while (!C.empty()) D.push(C.pop());

return D;

}