剑指:两个链表的第一个公共结点

题目描述

输入两个链表,找出它们的第一个公共结点。

样例

给出两个链表如下所示:
A:        a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3
输出第一个公共节点c1



解法

先遍历两链表,求出两链表的长度,再求长度差 |n1 - n2|

较长的链表先走 |n1 - n2| 步,之后两链表再同时走,首次相遇时的节点即为两链表的第一个公共节点。

 
/*
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 l1 = getLen(pHead1);
        int l2 = getLen(pHead2);
        
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        
        if(l1>l2){
            for(int i=0; i<l1-l2; i++){
                p1 = p1.next;
            }
        }else if(l1<l2){
            for(int i=0; i<l2-l1; i++){
                p2 = p2.next;
            }
        }
        
        while(p1!=p2 && p1!=null && p2!=null){
            p1 = p1.next;
            p2 = p2.next;
        }
        
        return (p1==null||p2==null)?null:p1;
    }
    
    private int getLen(ListNode head) {
        int n = 0;
        ListNode cur = head;
        while (cur != null) {
            ++n;
            cur = cur.next;
        }
        return n;
    }
}

 

 
posted @ 2019-09-23 16:39  亦海  阅读(143)  评论(0编辑  收藏  举报