二刷
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int len1 = 0; for(ListNode cur = pHead1; cur!=null;cur = cur.next) len1++; int len2 = 0; for(ListNode cur = pHead2; cur!=null;cur = cur.next) len2++; ListNode c1 = pHead1; ListNode c2 = pHead2; if(len1 > len2){ for(int i = len1-len2;i>0;i--){c1 = c1.next;} } else{ for(int i = len2-len1;i>0;i--){c2 = c2.next;} } while(c1!=c2){ c1 = c1.next; c2 = c2.next; } return c1; } }
1.没啥好说的 对其尾部, 从短的那个开始向后判断
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int smalllength; int length1 = 0; int length2 = 0; ListNode cur1; ListNode cur2; for(cur1 = pHead1;cur1!=null;cur1 = cur1.next){ length1++; } for(cur2 = pHead2;cur2!=null;cur2 = cur2.next){ length2++; } cur1 = pHead1; cur2 = pHead2; smalllength = length1 < length2 ? length1 : length2; if(smalllength == length1){ for(int i = length2-smalllength; i>0; i--){ cur2 = cur2.next; } } else{ for(int i = length1-smalllength; i>0; i--){ cur1 = cur1.next; } } while(cur1!=null && cur2!=null){ if(cur1 == cur2){ return cur1; } cur1 = cur1.next; cur2 = cur2.next; } return null; } }