Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Xóa phần tử thứ n từ head node trong C#

Thiết lập linked list và thêm phần tử:

Demo list = new Demo(); list.Push(50); list.Push(100); list.Push(150);

Xóa nth element từ head: truyền giá trị cần xóa. Nếu val=1 -> xóa head node.

Logic xóa

if (val == 1) { head = head.Next; return; }
Node n = head;      // node trước node cần xóa
Node m = head.Next; // node sẽ xóa
for (int i = 2; i < val; i++) { n = n.Next; m = m.Next; }
n.Next = m.Next;

Node n = head trỏ đến node trước node cần xóa.