Đặt LinkedList và thêm các phần tử.
string [] students = {"Beth","Jennifer","Amy","Vera"};
LinkedList<string> list = new LinkedList<string>(students); Trước hết, hãy thêm một nút mới vào cuối.
var newNode = list.AddLast("Emma"); Bây giờ, hãy sử dụng phương thức AddAfter () để thêm một nút sau nút đã cho.
list.AddAfter(newNode, "Matt");
Sau đây là mã hoàn chỉnh.
Ví dụ
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
string [] students = {"Beth","Jennifer","Amy","Vera"};
LinkedList<string> list = new LinkedList<string>(students);
foreach (var stu in list) {
Console.WriteLine(stu);
}
// adding a node at the end
var newNode = list.AddLast("Emma");
// adding a new node after the node added above
list.AddAfter(newNode, "Matt");
Console.WriteLine("LinkedList after adding new nodes...");
foreach (var stu in list) {
Console.WriteLine(stu);
}
}
} Đầu ra
Beth Jennifer Amy Vera LinkedList after adding new nodes... Beth Jennifer Amy Vera Emma Matt