📜  C#|删除LinkedList末尾的节点<T>

📅  最后修改于: 2021-05-29 18:28:57             🧑  作者: Mango

LinkedList < T > .RemoveLast方法用于删除LinkedList 末尾的节点。

句法:

public void RemoveLast ();

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

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

范例1:

// C# code to remove the node at
// the end 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 end of LinkedList
        myList.RemoveLast();
  
        // 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 : 
A
B
C
D

范例2:

// C# code to remove the node at
// the end 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 end of LinkedList
        // This should raise "InvalidOperationException"
        // as the LinkedList is empty
        myList.RemoveLast();
  
        // 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.removelast?view=netframework-4.7.2