判断链表是否有环

2020/01/02 119

算法 循环链表

判断单链表中是否有环

方法 1 C# 实现

class Program
{
    static void Main(string[] args)
    {
        var node1 = new Node(1);
        var node2 = new Node(2);
        var node3 = new Node(3);
        var node4 = new Node(4);
        var node5 = new Node(5);
        var node6 = new Node(6);

        node1.Next = node2;
        node2.Next = node3;
        node3.Next = node4;
        node4.Next = node5;
        node5.Next = node6;
        node6.Next = node3;

        Node p = node1;
        int count = 0;
        while (p.Next != null)
        {
            count++;
            p = p.Next;
            Node q = node1;
            for (int i = 0; i < count; i++)
            {
                q = q.Next;
                Console.WriteLine($"p: {p.No} q: {q.No}");
                if (p == q && i < count - 1)
                {
                    Console.WriteLine(true);
                    return;
                }
            }
        }
    }
}

class Node
{
    public int No { get; set; }
    public Node Next { get; set; }

    public Node(int no)
    {
        No = no;
    }
}
评论