Help Please! Use Stacks and Queues to transpose a string. (1) Use the JCF and St
ID: 3763212 • Letter: H
Question
Help Please!
Use Stacks and Queues to transpose a string.
(1) Use the JCF and Stacks to transpose the stack: "AA33BB66CC". You must only use stacks for this. The end result will be the stack: "B66CCAA33B". The strings will always be 10 characters long. The original string is placed on a stack, with "C" being the top.
(2) Use the JCF and Queues to transpose the queue: "AA11BB22CC". You must only use queues for this. The end result will be the queue: "B22CCAA11B". The strings will always be 10 characters long. The original string is placed in a queue, with "A" being the front.
(3) Output the original string and the transposed string with appropriate labels, e.g.
Using a Stack:
Original stack: [A,A,3,3,B,B,6,6,C,C]
Transposed stack: [B,6,6,C,C,A,A,3,3,B]
Using a Queue:
Original queue: [A,A,1,1,B,B,2,2,C,C]
Transposed queue: [B,2,2,C,C,A,A,1,1,B]
Explanation / Answer
import java.util.*;
public class StackDemo {
public static void main(String args[]) {
String s1 = "AA33BB66CC";
String s3 = "AA11BB22CC";
String s2="",s4="";
Stack st = new Stack();
for(int i=0;i<s1.length();i++)
{
st.push(s1.charAt(i));
}
System.out.print("Original stack: ");
System.out.println(st);
transposeStack(st);
System.out.print("Transposed stack: ");
System.out.println(st);
Queue q = new LinkedList();
for(int i=0;i<10;i++)
{
q.add(s3.substring(i,i+1));
}
System.out.print("Original Queue: ");
System.out.println(q);
transposeQueue(q);
System.out.print("Transposed Queue: ");
System.out.println(q);
}
public static void transposeStack(Stack st)
{
Stack st1 = new Stack();
Stack st2 = new Stack();
for(int i=0;i<5;i++)
{
st1.push(st.pop());
}
for(int i=0;i<5;i++)
{
st2.push(st.pop());
}
while(!st1.isEmpty())
st.push(st1.pop());
while(!st2.isEmpty())
st.push(st2.pop());
}
public static void transposeQueue(Queue q)
{
Queue q1 = new LinkedList();
Queue q2 = new LinkedList();
for(int i=0;i<5;i++)
q1.add(q.remove());
for(int i=0;i<5;i++)
q2.add(q.remove());
while(!q2.isEmpty())
q.add(q2.remove());
while(!q1.isEmpty())
q.add(q1.remove());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.