C# | Eliminación del Node al comienzo de LinkedList<T>

El método LinkedList< T >.RemoveFirst se usa para eliminar el Node al comienzo de LinkedList<T>.

Sintaxis:

public void RemoveFirst ();

Excepción: el método genera InvalidOperationException si LinkedList< T > está vacío.

A continuación se dan algunos ejemplos para entender la implementación de una mejor manera:

Ejemplo 1:

// C# code to remove the node at
// the start of the LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Strings
        LinkedList<String> myList = new LinkedList<String>();
  
        // Adding nodes in LinkedList
        myList.AddLast("A");
        myList.AddLast("B");
        myList.AddLast("C");
        myList.AddLast("D");
        myList.AddLast("E");
  
        // Displaying the nodes in LinkedList
        Console.WriteLine("The elements in LinkedList are : ");
  
        foreach(string str in myList)
        {
            Console.WriteLine(str);
        }
  
        // Removing the node at the start of LinkedList
        myList.RemoveFirst();
  
        // Displaying the nodes in LinkedList
        Console.WriteLine("The elements in LinkedList are : ");
  
        foreach(string str in myList)
        {
            Console.WriteLine(str);
        }
    }
}

Producción:

The elements in LinkedList are : 
A
B
C
D
E
The elements in LinkedList are : 
B
C
D
E

Ejemplo 2:

// C# code to remove the node at
// the start of the LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Integers
        LinkedList<int> myList = new LinkedList<int>();
  
        // Removing the node at the start of LinkedList
        // This should raise "InvalidOperationException"
        // as the LinkedList is empty
        myList.RemoveFirst();
  
        // Displaying the nodes in LinkedList
        Console.WriteLine("The elements in LinkedList are : ");
  
        foreach(int i in myList)
        {
            Console.WriteLine(i);
        }
    }
}

Error de tiempo de ejecución:

Excepción no controlada:
System.InvalidOperationException: LinkedList está vacío.

Nota: Este método es una operación O(1) .

Referencia:

Publicación traducida automáticamente

Artículo escrito por Sahil_Bansall 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 *