[编程题]两个链表的第一个公共结点

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

http://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46

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

    ListNode(int val) {
        this.val = val;
    }
}*/
/*
方法一利用hashmap
import java.util.HashMap;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        //定义两个指针
        if(pHead1==null||pHead2==null){
            return null;
        }
        ListNode p1=pHead1;
        ListNode p2=pHead2;
        HashMap<ListNode,Integer> hash=new HashMap<ListNode,Integer>();
        while(p1!=null){
            hash.put(p1,null);
            p1=p1.next;
        }
        ListNode result=null;
        while(p2!=null){
            if(hash.containsKey(p2)){
                result=p2;
                //结束整个循环
                break;
            }
            p2=p2.next;
        }
        return result;

    }
}*/


//方法二先计算两个链表的长度,如果有公共结点,则公共结点之后所有的结点都是公共结点
//因为每个链表只能有一个指针
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        //定义两个指针
        if(pHead1==null||pHead2==null){
            return null;
        }
        ListNode p1=pHead1;
        ListNode p2=pHead2;
        //计算两个链表的长度
        int lengthOfpHead1=0;
        int lengthOfpHead2=0;
        while(p1!=null){
            lengthOfpHead1++;
            p1=p1.next;
        }
           while(p2!=null){
            lengthOfpHead2++;
            p2=p2.next;
        }
  //因为上面求取长度时两个指针都位于末尾了,防止java.lang.NullPointerException**
      //p1与p2必须重新赋值**
        p1=pHead1;
        p2=pHead2;
        int differLength=lengthOfpHead1-lengthOfpHead2;
         ListNode result=null;
        if(differLength>=0){
            while(differLength>0){
                p1=p1.next;
                --differLength;
            }
            while(p2!=null){
                if (p1.next==null&&p2.next==null){
                result=null;
            }
                if(p1==p2){
                    result=p2;
                    break;
                }
                p1=p1.next;
                p2=p2.next;
            }
        }else{
                while(differLength<0){
                p2=p2.next;
                ++differLength;
            }
            while(p1!=null){
           if (p1.next==null&&p2.next==null){
                result=null;
            }
                if(p1==p2){
                    result=p1;
                    break;
                }
                p1=p1.next;
                p2=p2.next;
            }
        }
        return result;
    }
}

全部评论

相关推荐

03-26 13:04
已编辑
电子科技大学 算法工程师
xiaowl:你这个简历“条目上”都比较有深度性,但是实际上面试官又没法很好的评估你是怎么达到很多看上去很厉害的结果的。要避免一些看上去很厉害的包装,比如高效的内存复用策略的表达,如果仅是简单的一些内存共享机制,而且面试上也没有深挖的空间,就不要这样表达。比如,工程化模式本质上可能就是定义了一些abstract class,那也就没特别多值得讲的内容。建议简历上应该侧重那些你花了大量时间和精力解决、研究的问题,不要过分追求“丰富”,而是关注在技术深入度、问题解决能力的表现上。
没有实习经历,还有机会进...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务