Find Intersection point of 2 Linked List in c++ Algorithm

 

Algorithm:

  1. Initialize two pointers, pointerA and pointerB, to the heads of the two linked lists.

  2. Use a while loop to traverse both lists until we reach the end.

  3. Inside the loop, check if the current pointer (pointerA or pointerB) is at the end of its list. If it is, set it to the head of the other list.

  4. Compare the current pointerA and pointerB. If they are the same, return that node as the intersection point.

  5. If the pointers do not meet at any point, return null as the two lists do not intersect.

  6. The time complexity of this algorithm is O(n), where n is the total number of nodes in both lists.

  7. The space complexity is O(1) as we are only using two pointers, which do not take up any additional memory.

Example:

List 1: 1 -> 2 -> 3 -> 4 -> 5 -> 6 List 2: 7 -> 8 -> 9 -> 4 -> 5 -> 6

  1. Initialize pointerA to head of list 1 and pointerB to head of list 2.

  2. Traverse both lists using a while loop.

  3. Compare pointerA and pointerB. If they are the same, return that node as the intersection point (in this case, the node with value 4).

  4. If the pointers do not meet at any point, return null as the two lists do not intersect.

  5. The time complexity of this algorithm is O(n), where n is the total number of nodes in both lists (10 in this case).

  6. The space complexity is O(1) as we are only using two pointers, which do not take up any additional memory.

It's important to note that this algorithm assumes that the lists do not have a cycle. If the lists have a cycle, this algorithm may not work as expected and a different algorithm should be used.

Find Intersection point of 2 Linked List in c++  Algorithm