[Resuelto] Operaciones básicas de colas - Tarea Java (Colas)

  

3
Inicio del tema

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:

qum java

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.

1 respuesta
2

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

Here is a video about the Queues interface in Java:

Compartir: