码迷,mamicode.com
首页 > 编程语言 > 详细

C#数据结构与算法系列(五):常见单链表笔试

时间:2020-06-16 00:43:04      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:查找   heron   tin   ==   push   笔试   链表   pre   color   

1.求单链表中有效节点个数

        public static int GetLength(HeroNode headNode)
        {
            int length = 0;

            var cur = headNode.Next;

            while (true)
            {
                if (cur == null) break;

                length++;

                cur = cur.Next;
            }
            return length;
        }

2.查找单链表中倒数第N个节点

  public static HeroNode GetLastIndexNode(HeroNode headNode, int index)
        {
            var cur = headNode.Next;

            //if (cur == null) return null;

            int count = 0;

            while (true)
            {
                if (cur == null) break;

                count++;

                cur = cur.Next;
            }

            if (index <= 0 || index > count)
            {
                return null;
            }

            cur = headNode.Next;

            for (int i = 0; i < count - index; i++)
            {
                cur = cur.Next;
            }

            return cur;
        }

3.单链表反转

   public static  HeroNode  ReversetList(HeroNode headNode)
        {

            var cur = headNode.Next;

            if (cur == null) return null;

            var reversetNode = new HeroNode(0,"","");

            HeroNode next = null;

            while (cur!=null)
            {
                next = cur.Next;      
                
                cur.Next = reversetNode.Next;

                reversetNode.Next = cur;

                cur = next;
                
            }
return reversetNode; }

4.从尾到头打印单链表

        public static void ReversetPrint(HeroNode head)
        {
            var cur = head.Next;

            if (cur == null) return;

            Stack<HeroNode> stack = new Stack<HeroNode>();

            while (cur!=null)
            {
                stack.Push(cur);

                cur = cur.Next;
            }

            while (stack.Count>0)
            {
                var temp = stack.Pop();

                Console.WriteLine($"id={temp.Id},name={temp.Name},nickName={temp.NickName}");
            }
        }

 

 

C#数据结构与算法系列(五):常见单链表笔试

标签:查找   heron   tin   ==   push   笔试   链表   pre   color   

原文地址:https://www.cnblogs.com/vic-tory/p/13138640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!