+ 2

hi all programmer

i have this question : Suppose you have a deque D containing the numbers (1,2,3,4,5,6,7,8), in this order. Suppose further that you have an initially empty queue Q. Give a code fragment that uses only D and Q (and no other variables) and results in D storing the elements in the order (1,2,3,5,4,6,7,8). and I try to use this code: ArrayDeque<Integer> D = new ArrayDeque<>(); D.addAll(List.of(1, 2, 3, 4, 5, 6, 7, 8)); Queue<Integer> Q = new ArrayDeque<>(); while (!D.isEmpty()) { Q.offer(D.poll()); if (!D.isEmpty()) { D.offer(D.poll()); } } System.out.println("D: " + D); System.out.println("Q: " + Q); I want swapped just between 4 and 5 but I get wrong output why? please who can help me?

29th Dec 2023, 12:39 PM
deary
9 Answers
+ 2
deary I think D.offer(D.poll()); does nothing
2nd Jan 2024, 10:29 AM
Maram
+ 1
Rain yes it's right
29th Dec 2023, 1:11 PM
deary
0
deary , Did you word the problem right? It looks like you said D has to end up in the same state it started in.
29th Dec 2023, 12:42 PM
Rain
Rain - avatar
0
deary , Oh, I see. 4 and 5 are swapped. Would you remove all the extra language tags, and just leave the language tag that your code is in please?
29th Dec 2023, 2:02 PM
Rain
Rain - avatar
0
Is it a challenge. If so, please post at "Post your Coding Challenge Here". Please read the first post before posting anything. https://www.sololearn.com/discuss/1270852/?ref=app
29th Dec 2023, 2:48 PM
Wong Hei Ming
Wong Hei Ming - avatar
0
Wong Hei Ming this is not Challenge this is problem in this question and i put code in my post and your link are posted in answer is not working Thank you
29th Dec 2023, 6:37 PM
deary
0
Rain ok did you know about this question
29th Dec 2023, 6:41 PM
deary
0
deary , To address a comment to someone, type @ and choose them from the list of names that appears. Now that there's only one tag, I know it's a Java program. I took Introduction to Java here, but then I became a Python fan and switched, so I don't know ArrayDeque or Queue, but I'm looking on oracle.com about it. Your code is incomplete for Java. There's no main, etc. If you could post a link with the whole code intact, it would be easier to run and analyze. Meanwhile, maybe a Java fan will respond.
29th Dec 2023, 7:44 PM
Rain
Rain - avatar
0
deary , Do you know how to post a link to your code?
30th Dec 2023, 10:35 AM
Rain
Rain - avatar