C#实现链表的简单示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
List list = new List();
list.Add(new Node(1, “C#”));
list.Add(new Node(2, “Jave”));
list.Add(new Node(3, “Python”));
list.Print();
Console.WriteLine(“***********************************”);
list.Delect(2);
list.Print();
}
}

//定义结点
class Node
{
public Node(int id,string date)
{
this.Id = id;
this.Date = date;
}
public int Id { set; get; }
public string Date { set; get; }

public Node Next { set; get; }

public void Print()
{
Console.WriteLine(“Id:{0},Date:{1}”, this.Id, this.Date);
}
}

//定义链表
class List
{
Node head = null;
public List()
{
head = new Node(0,””);
}
public void Add(Node node)
{
Node temp = head;
while(true)
{
if(temp.Next==null)
{
break;
}
else
{
temp = temp.Next;
}
}
temp.Next = node;
}

public void Delect(int id)
{
Node temp = head;
while(true)
{
if(temp.Next==null)
{
break;
}
else
{
if(temp.Next.Id==id)
{
temp.Next = temp.Next.Next;
}
else
{
temp = temp.Next;
}
}
}
}
public void Print()
{
Node temp = head;
while (true)
{
if (temp.Next == null)
{
break;
}
else
{
temp = temp.Next;
temp.Print();
}
}
}
}
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注