剑指Offer面试题37

这题的难点在于理解单链表中如果有第一个公共节点,那么其后的所有节点都重合。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1 == null || pHead2 == null){
            return null;
        }

        //记录它们的长度可以不用两个辅助栈,让长的先走,可以同时到链尾
        int nLen1 = GetListLength(pHead1);
        int nLen2 = GetListLength(pHead2);
        int nLenDif = nLen1 - nLen2;

        //不妨假定pHead1较长
        ListNode pListHeadLong = pHead1;
        ListNode pListHeadShort = pHead2;
        if(nLen2 > nLen2){
            pListHeadLong = pHead2;
            pListHeadShort = pHead1;
            nLenDif = nLen2 - nLen1;
        }

        //先在长链表上走几步,再同时在两个链表上遍历
        for(int i = 0; i < nLenDif; i ++){
            pListHeadLong = pListHeadLong.next;
        }

        while((pListHeadLong != null) && (pListHeadShort != null)
                && (pListHeadLong != pListHeadShort)){
            pListHeadLong = pListHeadLong.next;
            pListHeadShort = pListHeadShort.next;
        }

        //得到第一个公共结点
        return pListHeadLong;
    }

    private int GetListLength(ListNode pHead) {
        int nLen = 0;
        ListNode pNode = pHead;
        while(pNode != null){
            ++ nLen;
            pNode = pNode.next;
        }
        return nLen;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值