Monday, July 21, 2014

[More] Intersection of Two Linked List

Problem

There are two singly linked lists in a system. By some programming error the end node of one of the linked list got linked into the second list, forming a inverted Y shaped list. Write a program to get the point where two linked list merge.
Follow up:
Given two lists, determine if they are intersected ? In O(n) time and O(1) space, and do it in one iteration.


Algorithm

Let L1 = length of list 1, and L2 = length of list 2. Let L = min(L1, L2). Start from Lth last node of list 1 and list 2, compare each node. If node 1 == node 2, it is the first intersection of two lists. 


Code


No comments:

Post a Comment