C# -- LinkedList的使用 class Person { public Person() { } public Person(string name, int age, string sex) { this.Name = name; this.Age = age; this.Sex = ...
C# -- LinkedList的使用
private static void TestLinkList() { LinkedList<Person> linkListPerson = new LinkedList<Person>(); Person p = null; for (int i = 1; i < 10; i++) { p = new Person($"程式員{i}", i + 18,i%5==1?"女":"男"); //添加 linkListPerson.AddLast(p); //linkListPerson.AddFirst(p); } Console.WriteLine($"新增的總人數:{linkListPerson.Count}"); Console.WriteLine("-------------------------------------------------------------"); //遍歷 LinkedListNode<Person> linkNodePerson = linkListPerson.First; linkNodePerson.Value.SayHi(); while (linkNodePerson.Next!=null) { linkNodePerson = linkNodePerson.Next; linkNodePerson.Value.SayHi(); } Console.WriteLine("-------------------------------------------------------------"); //刪除 while (linkNodePerson.Value != null && linkListPerson.Count > 0) { linkNodePerson = linkListPerson.Last; Console.Write($"當前總人數:{linkListPerson.Count}, 即將移除:{linkNodePerson.Value.Name} --> "); linkListPerson.RemoveLast(); Console.WriteLine($"移除後總人數:{linkListPerson.Count}"); } }
class Person { public Person() { } public Person(string name, int age, string sex) { this.Name = name; this.Age = age; this.Sex = sex; } public string Name { get; set; } public int Age { get; set; } public string Sex { get; set; } public void SayHi() { Console.WriteLine("我是{0},性別{1},今年{2}歲了!", this.Name, this.Sex, this.Age); } }View Code