剑指 Offer 52. 两个链表的第一个公共节点

1. 题目描述
输入两个链表,找出它们的第一个公共节点。
2. 思路
(1)比较两个链表的长度,让长的先走,直到两个链表的长度相等;
(2)两个链表同时一起走,比较两个链表是否相等。如果相等,则返回结点。否则当遍历完时,返回null。
3. 代码

public class Solution {
	public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null || headB==null)
            return null;
        ListNode tempA = headA;
        ListNode tempB = headB;
        int numA = 0;
        int numB = 0;
        //链表A长度
        while(tempA!=null){
            numA++;
            tempA = tempA.next;
        }
        //链表B长度
        while(tempB!=null){
            numB++;
            tempB = tempB.next;
        }
        tempA = headA;
        tempB = headB;
        //A长,让A先走
        if(numA>numB){
            for(int i=0;i<numA-numB;i++){
                tempA = tempA.next;
            }
        }else{//B长,让B先找。长度相等时,不操作
            for(int i=0;i<numB-numA;i++){
                tempB = tempB.next;
            }
        }
        //同时遍历A和B,找到第一个公共结点则返回
        while(tempA!=null && tempB!=null){
            if(tempA == tempB)
                return tempA;
            tempA = tempA.next;
            tempB = tempB.next;
        }
        return null;//没有公共结点
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值