链表相交

108 阅读1分钟

1、题目描述

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。

图示两个链表在节点 c1 开始相交:

题目数据 保证 整个链式结构中不存在环。

注意,函数返回结果后,链表必须 保持其原始结构 。

示例 1:

示例 2:

示例 3:

2、做题思路

(1)首先要确定是否有交叉点。注意,两个相交链表的最后节点始终相同。一旦它们相交,之后的所有节点将相等。你可以通过遍历到每个链表的末尾并比较它们的尾节点来确定两个链表是否相交。
(2)如果两个链表长度相同,则可以在每个链表中向前遍历,直到找到一个公共的元素。面对不同长度的链表,则可以尝试使用两个链表长度之间的差异。 解题代码如下:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }
        ListNode temp1 = headA;
        ListNode temp2 = headB;
        int len1 = 0;
        int len2 = 0;
        while(temp1.next != null){
            temp1 = temp1.next;
            len1++;
        }
        len1++;
        while(temp2.next != null){
            temp2 = temp2.next;
            len2++;
        }
        len2++;
        if(temp1 != temp2){
            return null;
        }
        temp1 = headA;
        temp2 = headB;
        if(len1 > len2){
            for(int i = 0;i < len1-len2;i++){
                temp1 = temp1.next;
            }
        }
        else{
            for(int i = 0;i < len2-len1;i++){
                temp2 = temp2.next;
            }
        }
        while(temp1 != temp2){
            temp1 = temp1.next;
            temp2 = temp2.next;
        }
        return temp1;
    }
}