[C#] Linked List Cycle 解法

       static void Main(string[] args)       {           HasCycle();       }       public class ListNode       {           public int val;           public ListNode next;           public ListNode(int x) { val = x; }       }       private static void HasCycle()       {           //  3 -> 2 -> 0 -> -4           ListNode head = new ListNode(3);           head.next = new ListNode(2);           head.next.next = new ListNode(0);           head.next.next.next = new ListNode(-4);           // 使得环 -4 指向 2           head.next.next.next.next = head.next;           bool result = HasCycle(head);           Console.WriteLine(result ? "有环." : "没环");           Console.ReadKey();       }       public static bool HasCycle(ListNode head)       {           if (head == null || head.next == null)           {               return false;           }           ListNode slow = head;           ListNode fast = head.next;           while (slow != fast)           {               if (fast == null || fast.next == null)               {                   return false;               }               slow = slow.next;               fast = fast.next.next;           }           return true;       }

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章