C# | Removing the node at the start of the LinkedList<T>
LinkedList<T>.RemoveFirst method is used to remove the node at the start of the LinkedList<T>.
Syntax:
public void RemoveFirst ();
Exception: The method throws InvalidOperationException if the LinkedList<T> is empty.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
public static void Main()
{
LinkedList<String> myList = new LinkedList<String>();
myList.AddLast( "A" );
myList.AddLast( "B" );
myList.AddLast( "C" );
myList.AddLast( "D" );
myList.AddLast( "E" );
Console.WriteLine( "The elements in LinkedList are : " );
foreach ( string str in myList)
{
Console.WriteLine(str);
}
myList.RemoveFirst();
Console.WriteLine( "The elements in LinkedList are : " );
foreach ( string str in myList)
{
Console.WriteLine(str);
}
}
}
|
Output:
The elements in LinkedList are :
A
B
C
D
E
The elements in LinkedList are :
B
C
D
E
Example 2:
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
public static void Main()
{
LinkedList< int > myList = new LinkedList< int >();
myList.RemoveFirst();
Console.WriteLine( "The elements in LinkedList are : " );
foreach ( int i in myList)
{
Console.WriteLine(i);
}
}
}
|
Runtime Error:
Unhandled Exception:
System.InvalidOperationException: The LinkedList is empty.
Note: This method is an O(1) operation.
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...