今天为大家带来一道题目:
这个题目先来看看我自己写的错误版本
public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode tmp1=pHead1; ListNode tmp2=pHead2; while(pHead1!=null&&pHead2!=null){ ListNode cur=tmp1; if(tmp1.val!=tmp2.val){ tmp1=tmp1.next; tmp2=tmp2.next; } return cur; } if(pHead1!=null){ return pHead1; } if(pHead2!=null){ return pHead2; } } }
这是错误的写法
来看正确的写法
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode l1 = pHead1, l2 = pHead2;
while(l1 != l2){
l1 = (l1==null)?pHead2:l1.next;
l2 = (l2==null)?pHead1:l2.next;
}
return l1;
}
}
遍历了链表1和链表2,一旦相遇就退出