LeetCode-160. Intersecting linked lists

Insert image description here
This is a really clever question. The solution is as follows:
if they line up at the end, then traversing from the back will quickly find the first intersection point. But reversing the order is troublesome.
So a clever idea was born. If the short one walks first and then the long one, and the long one walks after the short one, they will be exactly aligned.
then:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    
    public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
    
    
        ListNode l1 = headA, l2 = headB;
            while(l1 != l2)
            {
    
    
                l1 = l1.next;
                l2 = l2.next;

                //无相交
                if (l1 == null && l2 == null) break;
                //不等长交换
                if (l1 == null) l1 = headB;
                if (l2 == null) l2 = headA;

            }
            return l1;
    }
}

Guess you like

Origin blog.csdn.net/abaidaye/article/details/132558993