160. Intersection of Two Linked Lists

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

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

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

这道题要做的是找两个链表是否有交点,有的话返回交点,没有的话返回NULL。

解决方法:

1.设置两个指针cur1 = headA, cur2 = headB, 假设链表headA长度为L1, headB长度为L2,L2 > L1

2.两个指针cur1和cur2同时向下走,当cur2碰到尾部节点时,令cur1 = headB,然后cur1和cur2继续走,当cur2碰到尾部节点时,令cur2 = headA

如:

一开始cur1指向headA头部,cur2指向headB头部

两则同时移动,由于L1小于L2,cur1会先到达尾部,这时注意到,由于走了L1步,这时候cur2距离链表结尾为L2 - L1

然后下一步将cur1变成headB,这时候cur2也走到尾部

再将cur2设置为headA,同时cur1也往前走,这时候注意到,由于cur1是从headB头部开始走,而cur2走了L2 - L1步到达终点,那么cur1也走了L2-L1步,那么剩下的,cur1只要走L1步就能到达终点,而cur2在走的是headA的链表,长度为L1,那么可以知道,这两者会同时到达链表终点,而且如果有交点的话,也一定会遇到彼此

代码:

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (headA == NULL|| headB == NULL) return NULL;
        ListNode *cur1 = headA, *cur2 = headB;
        while (cur1 != cur2) {
            cur1 = cur1 ? cur1->next : headB;
            cur2 = cur2 ? cur2->next : headA;
        }
        return cur1;
    }
};
原文地址:https://www.cnblogs.com/linjj/p/5252534.html