Thêm nút (node) trước một nút cho trước trong C# dùng phương thức AddBefore().
LinkedList của chúng ta với các node chuỗi.
string[] students = {"Henry", "David", "Tom"};
LinkedList<string> list = new LinkedList<string>(students);
Bây giờ, hãy thêm node ở cuối.
// thêm node ở cuối
var newNode = list.AddLast("Brad");
Dùng phương thức AddBefore() để thêm node trước node 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);
}
// thêm node ở cuối
var newNode = list.AddLast("Brad");
// thêm node mới trước node thêm ở trên
list.AddBefore(newNode, "Emma");
Console.WriteLine("LinkedList sau khi thêm node mới...");
foreach (var stu in list) {
Console.WriteLine(stu);
}
}
}
Kết quả
Henry David Tom LinkedList sau khi thêm node mới... Henry David Tom Emma Brad