LinkedList
- AddLast(LinkedList
) - 加最后(T)
AddLast(LinkedListNode < T >)
此方法用于在LinkedList
句法:
public void AddLast (System.Collections.Generic.LinkedListNode node);
在此,节点是新的一个LinkedListNode
例外情况:
- ArgumentNullException:如果节点为null。
- InvalidOperationException:如果该节点属于另一个LinkedList < T >。
例子:
// C# code to add new node
// at the end of 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();
// Adding nodes in LinkedList
myList.AddLast(2);
myList.AddLast(4);
myList.AddLast(6);
myList.AddLast(6);
myList.AddLast(6);
myList.AddLast(8);
// To get the count of nodes in LinkedList
// before removing all the nodes
Console.WriteLine("Total nodes in myList are : " + myList.Count);
// Displaying the nodes in LinkedList
foreach(int i in myList)
{
Console.WriteLine(i);
}
// Adding new node at the end of LinkedList
// This will give error as node is null
myList.AddLast(null);
// To get the count of nodes in LinkedList
// after removing all the nodes
Console.WriteLine("Total nodes in myList are : " + myList.Count);
// Displaying the nodes in LinkedList
foreach(int i in myList)
{
Console.WriteLine(i);
}
}
}
运行时错误:
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: node
笔记:
- LinkedList < T >接受null作为引用类型的有效值,并允许重复值。
- 如果LinkedList < T >为空,则新节点将成为First和Last 。
- 此方法是O(1)操作。
AddLast(T)方法
此方法用于在LinkedList
句法:
public System.Collections.Generic.LinkedListNode AddLast (T value);
此处,值是要添加到LinkedList < T >末尾的值。
返回值:包含值的新LinkedListNode < T>。
例子:
// C# code to add new node containing
// the specified value at the end
// of 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();
// Adding nodes in LinkedList
myList.AddLast(2);
myList.AddLast(4);
myList.AddLast(6);
myList.AddLast(6);
myList.AddLast(6);
myList.AddLast(8);
// To get the count of nodes in LinkedList
// before removing all the nodes
Console.WriteLine("Total nodes in myList are : " + myList.Count);
// Displaying the nodes in LinkedList
foreach(int i in myList)
{
Console.WriteLine(i);
}
// Adding new node containing the
// specified value at the end of LinkedList
myList.AddLast(20);
// To get the count of nodes in LinkedList
// after removing all the nodes
Console.WriteLine("Total nodes in myList are : " + myList.Count);
// Displaying the nodes in LinkedList
foreach(int i in myList)
{
Console.WriteLine(i);
}
}
}
输出:
Total nodes in myList are : 6
2
4
6
6
6
8
Total nodes in myList are : 7
2
4
6
6
6
8
20
笔记:
- LinkedList < T >接受null作为引用类型的有效值,并允许重复值。
- 如果LinkedList < T >为空,则新节点将成为First和Last 。
- 此方法是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.linkedlist-1.addlast?view=netframework-4.7.2