Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method public static void transfer (StackX one, StackX two): It transfer

ID: 3757112 • Letter: W

Question

Write a method public static void transfer (StackX one, StackX two): It transfers all elements in the first parameter onto the top of the second parameter, keeping the same order. So what was initially on top of one ends up on top of two .

// stack.java
// demonstrates stacks
// to run this program: C>java StackApp
////////////////////////////////////////////////////////////////
class StackX
{
private int maxSize; // size of stack array
private long[] stackArray;
private int top; // top of stack
//--------------------------------------------------------------
public StackX(int s) // constructor
{
maxSize = s; // set array size
stackArray = new long[maxSize]; // create array
top = -1; // no items yet
}
//--------------------------------------------------------------
public void push(long j) // put item on top of stack
{
stackArray[++top] = j; // increment top, insert item
}
//--------------------------------------------------------------
public long pop() // take item from top of stack
{
return stackArray[top--]; // access item, decrement top
}
//--------------------------------------------------------------
public long peek() // peek at top of stack
{
return stackArray[top];
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return (top == -1);
}
//--------------------------------------------------------------
public boolean isFull() // true if stack is full
{
return (top == maxSize-1);
}
//--------------------------------------------------------------
} // end class StackX
////////////////////////////////////////////////////////////////
class StackApp
{
public static void main(String[] args)
{
StackX theStack = new StackX(10); // make new stack
theStack.push(20); // push items onto stack
theStack.push(40);
theStack.push(60);
theStack.push(80);

while( !theStack.isEmpty() ) // until it's empty,
{ // delete item from stack
long value = theStack.pop();
System.out.print(value); // display it
System.out.print(" ");
} // end while
System.out.println("");
} // end main()
} // end class StackApp
////////////////////////////////////////////////////////////////

Explanation / Answer

Please find the implementation below.

CODE

===============

public static void transfer(StackX one, StackX two) {

       StackX temp = new StackX(one.maxSize);

       while(!one.isEmpty()) {

           temp.push(one.pop());

       }

      

       while(!temp.isEmpty()) {

           two.push(temp.pop());

       }

   }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote