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());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.