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?