36.两个链表的第一个公共结点

题目描述
输入两个链表,找出它们的第一个公共结点。
1、解法1
首先,分别遍历两个链表,求出链表长度M、N,然后,让指向长链表的指针先走|M-N|步,然后,指向短链表的指针再往前走,当长短链表的指针指向同一个节点时,该节点就是他们的公共节点。

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int len1 = length(pHead1);
        int len2 = length(pHead2);
        if (len1 > len2){
            pHead1 = walk(pHead1, len1 - len2);
        } else {
            pHead2 = walk(pHead2, len2 - len1);
        }
        while (pHead1 != pHead2){
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }
        return pHead1;
    }
    int length(ListNode head) {
        int length = 0;
        while (head != null){
            length++;
            head = head.next;
        }
        return length;
    }
    ListNode walk(ListNode head, int i) {
        while (i-- != 0){
            head = head.next;
        }
        return head;
    }
}

2、解法2
把就两个链表连接起来,则连接起来的长度为M+N,这时候,无论短链表在前还是长链表在前,他们的公共节点部分一定是在连接链表的相同索引位置。例如:
1->3->5->7->9->10,2->7->9->10,按长短和短长两种方式连接后,得如下两个链表:
1->3->5->7 ->9->10->2->7->9->10
2->7->9->10->1-> 3->5->7-> 9->10
所以,有如下解法:

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode temp1 = pHead1;
        ListNode temp2 = pHead2;
        while (temp1 != temp2){
            /*
            if (temp1 == null)
                temp1 = pHead2;
            else
                temp1 = temp1.next;
            if (temp2 == null)
                temp2 = pHead1;
            else 
                temp2 = temp2.next;
            */
            //简洁写法,if...else...都可以这样写
            temp1 = (temp1 == null ? pHead2 : temp1.next);
            temp2 = (temp2 == null ? pHead1 : temp2.next);
        }
        return temp1;//当temp1 == temp2时,找到公共节点。
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值