Implement the class method public static void swap(Stack xs, Stack ys). The meth
ID: 3821624 • Letter: I
Question
Implement the class method public static void swap(Stack xs, Stack 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 a, b; a = new LinkedStack (); a.push("alpha"); a.push("beta"); a.push("gamma"); b = new DynamicArrayStack(); 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] public static void swap(Stack xs, Stack ys) {Explanation / Answer
// Please comment for any clearification or correction
import java.util.Stack;
public class SwapStacks<E> {
public static void main(String[] args) {
Stack<String> a = new Stack<String>();
Stack<String> b = new Stack<String>();
a.push("alpha");
a.push("beta");
a.push("gamma");
b.push("blue");
b.push("green");
b.push("yellow");
b.push("black");
System.out.println("---- BEFORE SWAP ---- ");
System.out.println("Stack a -> " + a);
System.out.println("Stack b -> " + b);
swap(a, b);
System.out.println(" ---- AFTER SWAP ---- ");
System.out.println("Stack a -> " + a);
System.out.println("Stack b -> " + b);
}
public static<E> void swap(Stack<E> s1, Stack<E> s2) {
swap(s1, s2, s1.size(), s2.size());
}
private static<E> void swap(Stack<E> s1, Stack<E> s2, int lenS1, int lenS2) {
if (s1.isEmpty() && s2.isEmpty()) return;
E s1Elem = null, s2Elem = null;
if (!s1.isEmpty())
s1Elem = s1.pop();
if (!s2.isEmpty())
s2Elem = s2.pop();
swap(s1, s2);
if (s1.size() < lenS2) s1.add(s2Elem);
if (s2.size() < lenS1) s2.add(s1Elem);
}
}