Algorithm to find if loop exist in LinkedList
Algo1: Take every node address of original LinkedList and add to visited LinkedList if it is not exist.
else print loop is found.
Time Complexity: O(n^2)
Space Complexity: O(n)
Algorithm 2:
1. Modify every node of the LL by inserting an extra field which is initially set to 0.
2. Visit every node of LL and verify
flag is 0 or not
if 0 , then make 1
else print loop exist
Time Complexity: O(n)
Space Complexity: O(n)
Algorithm 3:
1. Take 2-pointer p and q where p=q=list
2. Increase p by 1 and increase q by 2
3. if(p==q), then print loop found
else goto step 2
Time Complexity: O(n)
Space Complexity: O(1)
Implementation in C:
else print loop is found.
Time Complexity: O(n^2)
Space Complexity: O(n)
Algorithm 2:
1. Modify every node of the LL by inserting an extra field which is initially set to 0.
2. Visit every node of LL and verify
flag is 0 or not
if 0 , then make 1
else print loop exist
Time Complexity: O(n)
Space Complexity: O(n)
Algorithm 3:
1. Take 2-pointer p and q where p=q=list
2. Increase p by 1 and increase q by 2
3. if(p==q), then print loop found
else goto step 2
Time Complexity: O(n)
Space Complexity: O(1)
Implementation in C:
Comments
Post a Comment