Thêm một nút trước một nút nhất định trong C # bằng phương thức AddBefore ().
LinkedList của chúng tôi với các nút chuỗi.
string [] students = {"Henry","David","Tom"};
LinkedList<string> list = new LinkedList<string>(students); Bây giờ, hãy thêm nút vào cuối.
// adding a node at the end
var newNode = list.AddLast("Brad"); Sử dụng phương thức AddBefore () để thêm một nút trước khi nút được thêm ở trên.
list.AddBefore(newNode, "Emma");
Ví dụ
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
string [] students = {"Henry","David","Tom"};
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("Brad");
// adding a new node before the node added above
list.AddBefore(newNode, "Emma");
Console.WriteLine("LinkedList after adding new nodes...");
foreach (var stu in list) {
Console.WriteLine(stu);
}
}
} Đầu ra
Henry David Tom LinkedList after adding new nodes... Henry David Tom Emma Brad