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

我的思路:先求长度,每个长度长的遍历一次长度短的,

后看评论理解题意:第一个公共结点后面的都相同,所以可以先走长-短的差再比较。

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1 == null || pHead2 ==null)
        return null;
        else if(pHead1 != null && pHead2!=null){
            int i,j;                                        //求长度
            ListNode p1 = pHead1;
            ListNode p2 = pHead2;
            for(i=1; p1 != null; i++){
                p1 = p1.next;
            }
            for(j=1; p2 != null; j++){
                p2 = p2.next;
            }
            if(i>j){                                        //换位,减少代码量
                ListNode tem = pHead1;
                pHead1 = pHead2;
                pHead2 = tem;
            }  
            ListNode q1 = null; 
            while(pHead2 != null){                     
                q1 = pHead1;
                 while(q1 != null && pHead2.val != q1.val)           //注意判断的顺序,颠倒会发生nullpointerexception异常
                 {q1 = q1.next;}
                if(q1 != null && pHead2.val == q1.val) return pHead2;
                else pHead2 = pHead2.next;
            }
           
        }
  return null;
    }
}

 

简法:

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1 == null || pHead2 ==null)
        return null;
        else if(pHead1 != null && pHead2!=null){
            int i,j;                                        //求长度
            ListNode p1 = pHead1;
            ListNode p2 = pHead2;
            for(i=1; p1 != null; i++){
                p1 = p1.next;
            }
            for(j=1; p2 != null; j++){
                p2 = p2.next;
            }
            if(i>j){                                        //换位,减少代码量
                ListNode tem = pHead1;
                pHead1 = pHead2;
                pHead2 = tem;
            }  

           for(int z=j-i; z>0; z--){

                 pHead2 = pHead2.next;}


            while(pHead1 != pHead2){

                    pHead1 = pHead1.next;

                    pHead2 = pHead2.next;}

return pHead1;
           
        }
  return null;
    }
}

附大神解法:

class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
        ListNode *p1 = pHead1;
        ListNode *p2 = pHead2;
        while(p1!=p2){
            p1 = (p1==NULL ? pHead2 : p1->next);
            p2 = (p2==NULL ? pHead1 : p2->next);
        }
        return p1;
    }
};

posted on 2019-03-04 21:12  q2013  阅读(117)  评论(0编辑  收藏  举报

导航