static Node_no_constructor push(Node_no_constructor head_ref, int new_data) { // Allocate node Node_no_constructor new_node = new Node_no_constructor(); // Put in the data new_node.data = new_data; new_node.flag = 0; // Link the old list off the new node new_node.next = head_ref; // Move the head to point to the new node head_ref = new_node; return(head_ref); }
// Returns true if there is a loop in linked // list else returns false. static bool detectLoop_1(Node_no_constructor h) { while (h != null) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h.flag == 1) { return(true); } // If we are seeing the node for // the first time, mark its flag as 1 h.flag = 1; h = h.next; } return(false); }
/* Driver code*/ public static void Main(String[] args) { DetectLoop llist = new DetectLoop(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; if (detectLoop(llist.head)) { Console.WriteLine("Loop found"); } else { Console.WriteLine("No Loop"); } /* * Output * Loop found * Complexity Analysis: * * Time complexity: O(n). * Only one traversal of the loop is needed. * Auxiliary Space: O(n). * * n is the space required to store the value in hashmap. */ // Start with the empty list Node_no_constructor head = null; head = push(head, 20); head = push(head, 4); head = push(head, 15); head = push(head, 10); // Create a loop for testing head.next.next.next.next = head; if (detectLoop_1(head)) { Console.Write("Loop found"); } else { Console.Write("No Loop"); } /* * Output * Loop found * Complexity Analysis: * * Time complexity:O(n). * Only one traversal of the loop is needed. * Auxiliary Space:O(1). * * No extra space is needed.*/ }