Método Queue.Dequeue en C#

El método Dequeue() se utiliza para devolver el objeto al principio de la cola. Este método es similar al método Peek(). La única diferencia entre el método Dequeue y Peek es que el método Peek() no modificará la Cola, pero Dequeue sí lo hará. Este método es una operación O(1) y se incluye en el espacio de System.Collectionsnombres.

Sintaxis:

public virtual object Dequeue ();

Valor devuelto: Devuelve el objeto que se elimina del principio de la Cola.

Excepción: el método arroja InvalidOperationException al llamar a una cola vacía, por lo tanto, siempre verifique que el recuento total de una cola sea mayor que cero antes de llamar al método Dequeue().

Los siguientes programas ilustran el uso del método mencionado anteriormente:

// C# Program to illustrate the use 
// of Queue.Dequeue Method
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        Queue queue = new Queue();
        queue.Enqueue(3);
        queue.Enqueue(2);
        queue.Enqueue(1);
        queue.Enqueue("Four");
  
        Console.WriteLine("Number of elements in the Queue: {0}",
                                                    queue.Count);
  
        // Retrieveing top element of queue
        Console.WriteLine("Top element of queue is:");
        Console.WriteLine(queue.Dequeue());
  
        // printing the no of queue element 
        // after dequeue operation
        Console.WriteLine("Number of elements in the Queue: {0}",
                                                    queue.Count);
    }
}
Producción:

Number of elements in the Queue: 4
Top element of queue is:
3
Number of elements in the Queue: 3
// C# Program to illustrate the use 
// of Queue.Dequeue Method
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        Queue queue = new Queue();
  
        // Adding elements in Queue
        queue.Enqueue(2);
        queue.Enqueue("Four");
  
        Console.WriteLine("Number of elements in the Queue: {0}",
                                                    queue.Count);
  
        // Retrieveing top element of queue
        Console.WriteLine("Top element of queue is:");
        Console.WriteLine(queue.Dequeue());
  
        // printing the no. of queue element
        // after dequeue operation
        Console.WriteLine("Number of elements in the Queue: {0}",
                                                    queue.Count);
    }
}
Producción:

Number of elements in the Queue: 2
Top element of queue is:
2
Number of elements in the Queue: 1

Referencia:

Publicación traducida automáticamente

Artículo escrito por Twinkl Bajaj y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *