2.7 Intersection

Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting node. Note that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting.

Hint
  • You can do this in O(A+B) time and O(1) additional space. That is, you do not need a hash table (although you could do it with one).
  • Examples will help you. Draw a picture of intersecting linked lists and two equivalent linked lists (by value) that do not intersect.
  • Focus first on just identifying if there's an intersection.
  • Observe that two intersecting linked lists will always have the same last node. Once they intersect, all the nodes after that will be equal.
  • You can determine if two linked lists intersect by traversing to the end of each and comparing their tails.
  • Now, you need to find where the linked lists intersect. Suppose the linked lists were the same length. How could you do this?
  • If the two linked lists were the same length, you could traverse forward in each until you found an element in common. Now, how do you adjust this for lists of different lengths?
  • Try using the difference between the lengths of the two linked lists.
  • If you move a pointer in the longer linked list forward by the difference in lengths, you can then apply a similar approach to the scenario when the linked lists are equal.
Solution

本题要我们求出两个链表的交汇点,假设两个链表等长的话,那么使用两个指针同时遍历必然会有指向同一个结点的情况,那就是我们要找的交汇点。进一步假设两个链表不等长的话,我们只需要先分别计算出两个链表的长度差 k,让长链表的指针先移动 k 个位置,然后两个链表一起移动,此时就相当于它们等长了,若第一次相遇则就是交汇点。
还有一种非常巧妙的写法,我们让两条链表分别从各自的开头开始往后遍历,当其中一条遍历到末尾时,我们跳到另一个条链表的开头继续遍历。两个指针最终会相等,而且只有两种情况,一种情况是在交点处相遇,另一种情况是在各自的末尾的空节点处相等。因为两个指针走过的路程相同,就是两个链表的长度之和。

public ListNode getIntersectionNode(ListNode head1, ListNode head2) {
    if (head1 == null || head2 == null) return null;
    ListNode l1 = head1, l2 = head2;
    while (l1 != l2) {
        l1 = l1 == null ? head2 : l1.next;
        l2 = l2 == null ? head1 : l2.next;
    }
    return l1;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,296评论 3 20
  • 一个人的成功,不仅仅是靠自己努力就可以的,更重要的要素是时代,更多的原因也是时代,正所谓时势造英雄,识时务者为俊杰...
    精工_b347阅读 489评论 0 0
  • 茜茜宝贝,阿姨为有你而骄傲喜悦,永远爱你! 写这篇文章是有感于和妹妹的一次谈话和看到有关这段对话的茜宝贝的情绪随手...
    Daisy肖湘粤阅读 603评论 1 1
  • 年前差不多还有20天左右的时间办公室的装修还没有开始今天看了房子大概计算了需要的工作量觉得年前能做的太少了好在后天...
    哈哈同学阅读 138评论 0 0