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

For this question, there is an interface named Stack: public interface Stack { p

ID: 3915491 • Letter: F

Question

For this question, there is an interface named Stack:

public interface Stack {

public abstract void push( int item ); public abstract int pop ();

public abstract boolean isEmpty (); }

Implement the class method:    public static <E> void swap(Stack<E> xs , Stack<E> ys)

• The method exchanges the content of two stacks, xs and ys.

• The method must work for any valid implementation of the interface Stack;

• You can assume the existence of the classes DynamicArrayStack and LinkedStack.
Stack<String> a , b;

a = new LinkedStack<String >(); a . push(” alpha ”); a . push(” beta ”); a . push(”gamma”);

b = new DynamicArrayStack<String >(); b. push(” blue ”); b. push(” green ”); b. push(” yellow ”); b. push(” black ”);

System . out . println (a ); System . out . println (b);

swap(a , b);

System . out . println (a ); System . out . println (b );

In particular, the above statements should print the following:
[gamma, beta , alpha ]

[ black , yellow , green , blue ]

[ black , yellow , green , blue ]

[gamma, beta , alpha ]

Explanation / Answer

Please find the code below with detailed inline comments.

CODE

-==================

public static <E> void swap(Stack<E> xs , Stack<E> ys) {

// first create a temporary stack for storing the elements of xs

Stack<E> xsTemp = new Stack<E>();

while(xs.isEmpty()){

xsTemp.push(xs.pop());

}

// now create a temporary stack for storing the elements of ys

Stack<E> ysTemp = new Stack<E>();

while(ys.isEmpty()){

ysTemp.push(ys.pop());

}

// Now, put the elements of xsTemp into ys and ysTemp into xs

while(xsTemp.isEmpty()) {

ys.push(xsTemp.pop());

}

while(ysTemp.isEmpty()) {

xs.push(ysTemp.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