您的位置:首页 > Web前端

牛客:剑指offer:两个链表的第一个公共结点(Java)

2016-12-10 15:03 288 查看
题目:



看到这个题,我想到的就是最笨的办法,先遍历两个链表,算出各自的长度,然后让长的链表先走Math.abs(l1-l2)步,然后两个指针再一起走,当指向同一个节点时就找到了公共节点。

虽然觉得这个办法太老了,但是暂时也没有想到新方法。

/*
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);
if(l1 > l2)
return getCon(pHead1,pHead2,l1-l2);
return getCon(pHead2,pHead1,l2-l1);
}
public int getLen(ListNode tmp){
int res = 0;
while(tmp != null){
res++;
tmp = tmp.next;
}
return res;
}
public ListNode getCon(ListNode p1,ListNode p2,int len){
for(int i = 0; i < len; i++){
p1 = p1.next;
}
while(p1 != null && p2 != null){
if(p1.val == p2.val)
return p1;
p1 = p1.next;
p2 = p2.next;
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: