Here is my runnable code.
What I have done is to reveres the linked list by using three temporary nodes (space complexity O(1)
) that keep track of the links.
The interesting fact about doing it is to help detect the cycle in the linked list because as you go forward, you don't expect to go back to the starting point (root node) and one of the temporary nodes should go to null unless you have a cycle which means it points to the root node.
The time complexity of this algorithm is O(n)
and space complexity is O(1)
.
Here is the class node for the linked list:
public class LinkedNode{
public LinkedNode next;
}
Here is the main code with a simple test case of three nodes that the last node pointing to the second node:
public static boolean checkLoopInLinkedList(LinkedNode root){
if (root == null || root.next == null) return false;
LinkedNode current1 = root, current2 = root.next, current3 = root.next.next;
root.next = null;
current2.next = current1;
while(current3 != null){
if(current3 == root) return true;
current1 = current2;
current2 = current3;
current3 = current3.next;
current2.next = current1;
}
return false;
}
Here is the a simple test case of three nodes that the last node pointing to the second node:
public class questions{
public static void main(String [] args){
LinkedNode n1 = new LinkedNode();
LinkedNode n2 = new LinkedNode();
LinkedNode n3 = new LinkedNode();
n1.next = n2;
n2.next = n3;
n3.next = n2;
System.out.print(checkLoopInLinkedList(n1));
}
}
finite amount of space and a reasonable amount of time?
:) – codaddict