resources is anowcu. Problem #1 (25%) suppose you have three non-empty stacks R,
ID: 3839697 • Letter: R
Question
resources is anowcu. Problem #1 (25%) suppose you have three non-empty stacks R, s, and T. Describe a sequence of stack operations that results in S storing all elements originally in T below all of S's original elemen with both sets of those elements in their original order. The final configuration for R should be the same as its original configuration. For example, if R (1,2,3), S (4,5), and T (6, 7, 8, when ordered from bottom to top, then the final configuration should have R (1,2,3), and S (6,7,8,9,4,5).Explanation / Answer
import java.util.*;
public class HelloWorld{
public static void main(String args[]) {
Stack R = new Stack();
Stack S = new Stack();
Stack T = new Stack();
/// INitialize the Stacks S, R T
R.push(1);
R.push(2);
R.push(3);
System.out.println("stack R: " + R);
S.push(4);
S.push(5);
System.out.println("stack S: " + S);
T.push(6);
T.push(7);
T.push(8);
T.push(9);
System.out.println("stack T: " + T);
int count = 0;
while(!T.empty()) // Empty the stack T and push contents to R
{
count++; //Keep a count of number of elements in T
R.push(T.pop());
}
while(!S.empty())
T.push(S.pop()); //Empty the stack S and push contents to T
for(int i=1; i<= count; i++) // Now pop the elments from R and push to S,
S.push(R.pop()); //do this count number of times
while(!T.empty()) //Empty the stack T and push contents to S
S.push(T.pop());
System.out.println("After sequence of operations");
System.out.println("stack S: " + S);
System.out.println("stack R: " + R);
System.out.println("stack T: " + T);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.