【Leetcode】160.相交链表-CSDN博客

93 阅读1分钟

相交链表

在这里插入图片描述
思路

  1. 先求出每段单链表的长度 包括重复的部分
  2. 让较长的那条链表的指针往前走两条链表长度的差值步
  3. 两条链表的指针在同时向前走 直到指针指向的节点相同则返回这个节点
  4. 如果指针走到最后一个节点都没有相遇 则没有相交节点

代码实现

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headB == null && headA != null){
            return null;
        }
        if(headB != null && headB == null){
            return null;
        }
        //如果有一个链表为空 则直接返回null
        ListNode plong = headA;
        ListNode pshort = headB;
        //默认headA比headB长
        int len1 = 0;
        int len2 = 0;
        //len1表示headA的长度
        //len2表示headB的长度
        while(plong != null){
            plong = plong.next;
            len1++;
        }
        while(pshort != null){
            pshort = pshort.next;
            len2++;
        }
        //求长度
        plong = headA;
        pshort = headB;
        //将两个链表的指针在指回头节点
        int len = len1 - len2;
        //求两个长度的差值
        if(len < 0){
        //如果差值小于0 则说明我们默认错误 头节点为headB的链表菜市场链表
            plong = headB;
            pshort  = headA;
            len = len2 - len1;
        //把headB改为long链表
        }
        while(len != 0){
            plong = plong.next;
            len --;
            //长的链表先走差值步
        }
        while(plong != pshort){
        //在同时走 直到指向同一个节点
            plong = plong.next;
            pshort = pshort.next;
        }
        return plong;
    }
}