C# -- LinkedList的使用


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM