[LeetCode] Intersection of Two Linked Lists

Question:

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.

1、题型分类:

2、思路:

3、时间复杂度:O(n)

4、代码:

空间复杂度O(n)

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null || headB==null) return null;
        Set<ListNode> set=new HashSet<ListNode>();
        while(headA!=null)
        {
            if(set.contains(headA)) return headA;
            else set.add(headA);
            headA=headA.next;
        }
        while(headB!=null)
        {
            if(set.contains(headB)) return headB;
            else set.add(headB);
            headB=headB.next;
        }
        return null;
    }
}

5、优化:

先计算两个链表的长度,然后分别从相同长度的节点开始遍历,遇到相同的元素返回。

public class Solution {
    
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = getLen(headA);
        int lenB = getLen(headB);
        
        ListNode shortHead = headA;
        ListNode longHead = headB;
        if (lenA > lenB) {
            shortHead = headB;
            longHead = headA;
        }
        
        int i = 0;
        while (i < Math.abs(lenB - lenA)) {
            i++;
            longHead = longHead.next;
        }
        
        while (shortHead != longHead) {
            shortHead = shortHead.next;
            longHead = longHead.next;
            
            
            if (shortHead == null) {
                return null;
            }
        }
        return shortHead;
    }
    
    private int getLen(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }
}

6、扩展:

原文地址:https://www.cnblogs.com/maydow/p/4644150.html