public class TestStack { public static void test(Stack<String> s) { Stack<String
ID: 3891881 • Letter: P
Question
public class TestStack {
public static void test(Stack<String> s) {
Stack<String> tmp;
tmp = new LinkedStack<String>();
while (! s.isEmpty()) {
tmp.push(s.pop());
}
s = tmp;
}
public static void main(String[] args) {
Stack<String> s;
s = new LinkedStack<String>();
s.push("A");
s.push("B");
s.push("C");
s.push("D");
System.out.println("before:");
System.out.println(s);
test(s);
System.out.println("after:");
System.out.println(s);
}
}
Complete the print out resulting from the execution of the code above. before:
[A,B,C,D] <- top
Explanation / Answer
Initially stack s
[ ] <- top
After
s.push("A");
s.push("B");
s.push("C");
s.push("D");
Stack s is
top -> [ D , C , B , A ]
A is at the bottom and D is at the top.
So, the output of
System.out.println("before:");
System.out.println(s);
is
before:
[ D , C , B , A ]
Now the test() function reverses the stack s passed as argument.
So, the Stack s after the test() function is
top -> [ A , B , C , D ]
So, the output of
System.out.println("after:");
System.out.println(s);
is
after:
[ A , B , C , D ]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.