Computer >> Máy Tính >  >> Lập trình >> C#

Phương thức Xóa LinkedList trong C #

Sử dụng phương thức Remove () để xóa lần xuất hiện đầu tiên của một nút trong Danh sách liên kết.

Trước tiên, hãy để chúng tôi đặt một LinkedList với các phần tử số nguyên.

int [] num = {2, 5, 7, 15};
LinkedList<int> list = new LinkedList<int>(num);

Bây giờ, giả sử bạn cần xóa nút có phần tử 7. Để làm điều đó, hãy sử dụng phương thức Remove ().

list.Remove(7);

Hãy cho chúng tôi xem mã hoàn chỉnh.

Ví dụ

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      int [] num = {2, 5, 7, 15};
      LinkedList<int> list = new LinkedList<int>(num);
      foreach (var n in list) {
         Console.WriteLine(n);
      }
      // adding a node at the end
      var newNode = list.AddLast(25);
      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var n in list) {
         Console.WriteLine(n);
      }
      // removing
      list.Remove(7);
      Console.WriteLine("LinkedList after removing a node...");
      foreach (var n in list) {
         Console.WriteLine(n);
      }
   }
}

Đầu ra

2
5
7
15
LinkedList after adding new nodes...
2
5
7
15
25
LinkedList after removing a node...
2
5
15
25