📜  C#|在LinkedList的开头删除节点<T>

📅  最后修改于: 2021-05-29 21:33:23             🧑  作者: Mango

LinkedList < T > .RemoveFirst方法用于删除LinkedList 开头的节点。

句法:

public void RemoveFirst ();

异常:如果LinkedList < T >为空,则该方法将引发InvalidOperationException。

下面给出了一些示例,以更好地理解实现:

范例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 myList = new LinkedList();
  
        // 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);
        }
    }
}

输出:

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

范例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 myList = new LinkedList();
  
        // 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);
        }
    }
}

运行时错误:

注意:此方法是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.linkedlist-1.removefirst?view=netframework-4.7.2