Dear Experts, my program output as below is not exactly folows as required.Pls m
ID: 3583929 • Letter: D
Question
Dear Experts,
my program output as below is not exactly folows as required.Pls modify the program in order to get exactly as required in question. Thanks.
Front [1, 2, 3] Back
Front [1, 1, 2, 2, 3, 3] Becomes
Front [a, b, c]
Front [c, b, a] BackBUILD SUCCESSFUL (total time: 0 seconds)
the questions and output required as follows:
Write a method stutter that accepts a queue of integers as a parameter and replaces every element of the queue with two copies of that element.
front [1, 2, 3] back
becomes
front [1, 1, 2, 2, 3, 3] back
Write a method mirror that accepts a queue of strings as a parameter and appends the queue's contents to itself in reverse order.
front [a, b, c] back
becomes
front [a, b, c, c, b, a] back
My Program as below:
package javaapplication32;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class stutter {
public static void main(String[] args){
Queue<Integer>q=new LinkedList<>();
q.add(1);
q.add(2);
q.add(3);
System.out.println("Front " + q + " Back");
stutter(q);
System.out.println("Front " + q + " Becomes");
LinkedList m = new LinkedList();
m.add("a");
m.add("b");
m.add("c");
System.out.println("Front " + m );
mirror(m);
System.out.print("Front " + m + " Back" );
}
public static void stutter (Queue<Integer> q){
int length=q.size();
for (int i=0;i<length;i++){
int element=q.remove();
q.add(element);
q.add(element);
}
}
static void mirror(LinkedList<String> m){
int size = m.size();
Stack<String> s = new Stack<>();
for(int i=0;i<size;i++){
String val=m.remove();
s.push(val);
}
while(!s.isEmpty())
{
m.add(s.pop());
}
}
}
Explanation / Answer
//changed mirror function
static void mirror(LinkedList<String> m){
int size = m.size();
//Added by Chegg EA, Created two stacks s1 and s2
Stack<String> s1 = new Stack<>();
Stack<String> s2 = new Stack<>();
//added by Chegg EA
for(int i=0;i<size;i++){
String val = m.removeFirst();
s1.push(val);
s2.push(val);
}
//added by Chegg EA
for(int i=0;i<size;i++){
String val=s1.pop();
s2.push(val);
}
while(!s2.isEmpty())
{
m.add(s2.pop());
}
}
-----------------------------------------------------------------------------------------------------------
output
Front [1, 2, 3] Back
Front [1, 1, 2, 2, 3, 3] Becomes
Front [a, b, c] Back
Becomes
Front [a, b, c, c, b, a] Back
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.