Check if two Circular Linked Lists are identical
Given two circular linked lists L1 and L2, the task is to find if the two circular linked lists are identical or not.
Note: Head of any linked list points to any node of the respective linked list and the lists can contain duplicate elements.
Input: L1: 1 -> 2 -> 3 -> 4 -> 5 -> 1 -> 2 -> 6
L2: 5 -> 1 -> 2 -> 6 -> 1 -> 2 -> 3 -> 4
Explanation: If checked the 5th element of L1 and 1st element of L2 then they are identical.
As they are circular, does not matter from where we start checking.
Input: L1: 1 -> 2 -> 3
L2: 1 ->3 -> 2
Approach: The problem can be solved by traversing the circular linked list using the following idea:
Fix the starting point of any list. Now consider every element of the other list as head and compare if both the lists are identical or not for that starting point.
Follow the steps to mentioned below to solve the problem:
- Calculate, length l1 and l2 of both the circular linked lists respectively
- If both the length are different then return false
- Initialize Count = 0, flag = false
- Initialize temporary pointers, h1 and h2 for head1 (starting pointer of l1) and head2 (starting pointer of l2)
- Traverse while it does not return a bool, true or false:
- If, data of h1 is equal to data of h2 then shift the h1 and h2 to its next node and increase the count by 1.
- If Count equals to l1 (or l2) then linked lists are identical, return true
- Else, reset the pointer h1 and variable count to their initial state.
- If, flag == 1, return false as it means one rotation is completed, and now if element does not matches then list can not be identical.
- If, h2->next = head2 then one rotation is complete, then set, flag = 1
- Move h2 pointer by 1 position, h2 = h2->next.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)