160. Intersection of Two Linked Lists

problem description

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

begin to intersect at node c1.

Example 1:

Example 2:

Example 3:

Notes:

If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory.

algorithm thought

这里如果使用一个hashmap保存所有节点,很简单就能得到答案,但是空间复杂度是O(n),这里要求使用O(1)的空间复杂度解题,首先我们遍历两个链表,得到两个链表的长度,如果有一个长一个短,首先让长的链表头节点先移动两链表的差值,这时候两个链表一样长了,只需要一起移动,并且每次都判断是否为同一个节点即可。

update:更新图片的时候,发现discuss有更好的算法,我这里需要3次遍历链表,其实开始两次得到链表长度的目的就是让两个链表能同步开头,最后一起结束,还有一种办法能达到这个目的。两个链表一起移动,到达尾节点的时候,两个链表交换继续执行。也就是A到尾节点的时候,领tmpA=HeadB,B到尾节点的时候,令tmpB=HeadA。这样,也能消除两个链表之间的差距

code

algorithm analysis

遍历了很多次链表,时间复杂度是O(n),没有用额外的空间,空间复杂度O(1)

Last updated