示例#1
0
        static void Main(string[] args)
        {
            //
            // Question 2.6
            //
            // Given a circular linked list, implement an algorithm which returns
            // the node at the beginning of the loop.
            // DEFINITION
            // Circular linked list: A (corrupt linked list in which a node's next pointer
            // points to an earlier node, so as to make a loop in the linked list.
            // EXAMPLE
            // Input: A -> B -> C -> D -> E -> C [the same C as earlier]
            // Output: C
            //

            Random rand = new Random();
            Node valid_list = new Node(400);
            for (int x = 0; x <= 4; x++)
            {
                valid_list.appendToTail(rand.Next(0, 100));
            }
            Console.WriteLine("Valid list: ");
            print_node(valid_list);

            Node bork = find_circular_reference(valid_list);

            if (bork != null) { Console.WriteLine("Found circular reference: " + bork.data); }

            Node corrupt_list = new Node(500);
            for (int x = 0; x <= 4; x++)
            {
                corrupt_list.appendToTail(rand.Next(0, 50));
            }
            Node circular = corrupt_list.next.next;

            Node runner = corrupt_list;
            while (runner.next != null)
            {
                runner = runner.next;
            }
            runner.next = circular;

            Console.WriteLine("Corrupt list: ");
            print_node(corrupt_list);

            bork = find_circular_reference(corrupt_list);

            if (bork != null) { Console.WriteLine("Found circular reference: " + bork.data); }

            Console.ReadLine();
        }