
C Sc 127B In-Class Activity, 2-March-2007 (8 minutes)
Form a team of two.
Neatly print both of your full names (first name and last name):
a. _______________________________ b. ___________________________
Choose the scribe (the person writing the answer) as the person who woke up later today.
Moksha Zack Josh Will
Complete method reverseStack that reverses the elements of a Stack
public void reverseStack (Stack<String> s ) {
Correct Answer with a test method below
public void reverseStack(Stack<String> st) {
ArrayList<String> temp =
new ArrayList<String>();
while (!st.empty()) {
temp.add(st.pop());
}
for (int i = 0; i < temp.size(); i++)
st.push(temp.get(i));
}
An incorrect solution. Why?
public void reverseStack(Stack<String> st) {
Stack<String> temp = new Stack<String>();
while (!st.empty()) {
temp.push(st.pop());
}
temp = st;
}
@Test
public void testReverseStack() {
Stack<String> s = new Stack<String>();
s.push("a");
s.push("b");
s.push("c");
s.push("d");
assertEquals("d", s.peek());
reverseStack(s);
assertEquals("a", s.peek());
assertEquals("a", s.pop());
assertEquals("b", s.pop());
assertEquals("c", s.pop());
assertEquals("d", s.pop());
}
public void reverseStack(Stack<String> st) {
Stack<String> temp = new Stack<String>();
while (!st.isEmpty()) {
temp.push(st.pop());
}
st = temp;
}