0
点赞
收藏
分享

微信扫一扫

【leetcode打卡】链表相交

辰鑫chenxin 2022-05-05 阅读 46

链表相交

链表相交

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        
        int lenA=0,LenB=0;
        ListNode curA=headA;
        ListNode curB=headB;
        //计算两个链表的长度
        while(curA!=null){
            lenA++;
            curA=curA.next;
        }
        while(curB!=null){
            LenB++;
            curB=curB.next;
        }
        curA=headA;
        curB=headB;
        //统一规则,链表A较长
        if(LenB>lenA){
            int teamLen=lenA;
            lenA=LenB;
            LenB=teamLen;

            ListNode team=curA;
            curA=curB;
            curB=team;
        }
         
        //计算差值
        int gap=lenA-LenB;
        //对应末尾
        while(gap-->0){
            curA=curA.next;
        }
        //遍历连个链表,相同结点就返回该节点
        while(curA!=null){
            if(curA==curB){
                return curA;
            }
            curA=curA.next;
            curB=curB.next;
        }
        return null;
    }
}
举报

相关推荐

0 条评论