搜索此博客

2011年2月23日星期三

Check whether there is the intersection of two linked lists

Given the heads of two linked lists, judge whether there is the intersection of two linked list.

Extend Question:
1. If there is a ring in the linked list, how do you change?
2. Can you find the first intersection node?

Two solutions:
1. We can connect the head of the second linked list to the tail of the first linked list. If there is a ring existing into the new linked list, two linked lists intersects.
Thus, we translated the problem into another problem that checks there is the ring of two linked lists.

2. Firstly, we can travel the first linked list and remember the last node, then travel the next linked list to get the last node. We compare the two last nodes. If they are the same, two linked list intersects.
Time: O(Length(h1)+Length(h2))

After we travels two linked lists, we attain their lengths of two linked lists. The longer one moves (LengthMax - LengthMin), then two linked list move together. If they can find the first same node, it should be the first node they intersects.

没有评论:

发表评论