settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Basic Queue Operations - Java Task (Queues)

+14 votes

Play around with a queue.

You will be given:

  • An integer N representing the amount of elements to enqueue (add)
  • An integer S representing the amount of elements to dequeue (remove/poll) from the queue
  • An integer X, an element that you should check whether is present in the queue.

If it is print true on the console, if it’s not print the smallest element currently present in the queue. If the stack is empty print 0.

Examples:

Input

Output

5 2 32

1 13 45 32 4

true

 

4 1 665

665 69 13 420

13

3 3 90

90 90 90

0

 

For the 1st task (with 5 2 32...) comment: We have to push 5 elements. Then we pop 2 of them. Finally, we have to check whether 32 is present in the stack. Since it is we print true.

asked in Java category by user sam
edited by user golearnweb

2 Answers

+2 votes
 
Best answer

Here is the answer:

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;

public class Pr_04_BasicQueueOperations {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String[] inputNumbers = sc.nextLine().split(" ");
        int min = Integer.MAX_VALUE;

        Queue<Integer> queue = new ArrayDeque<>();

        int n = Integer.parseInt(inputNumbers[0]);
        int s = Integer.parseInt(inputNumbers[1]);
        int x = Integer.parseInt(inputNumbers[2]);

        for (int i = 0; i < n; i++) {
            int currentNumber = sc.nextInt();
            queue.add(currentNumber);
            if (currentNumber <= min) {
                min = currentNumber;
            }
        }

        for (int i = 0; i < s; i++) {
            queue.remove();
        }

        if (queue.contains(x)) {
            System.out.println("true");
        } else if (queue.size() == 0) {
            System.out.println("0");
        } else {
            System.out.println(min);
        }
    }
}

Here you can read more about Queues in Java: https://docs.oracle.com/javase/tutorial/collections/implementations/queue.html

answered by user eiorgert
edited by user golearnweb
+1 vote

Here is a video about the Queues interface in Java:

https://www.youtube.com/watch?v=KKN4zh7T3JE

answered by user nikole
edited by user golearnweb
...