解法1:
public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {// 定义两个指针。// 获得两个链表的长度,将较长的链表先用指针移动到和短链表一样的长度。// 再一个个比较ListNode l1 = headA, l2 = headB;int len1 = 0, len2 = 0;while(headA != null){len1++;headA = headA.next;} while(headB != null){len2++;headB = headB.next;}while(len1 > len2){l1 = l1.next;len1--;}while(len1 < len2){l2 = l2.next;len2--;}while(l1 != l2){l1 = l1.next;l2 = l2.next;}return l1;}
}
解法2:(自己写法)
结合图片理解一下:
public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {ListNode l1 = headA, l2 = headB;while(l1 != null && l2 != null){l1 = l1.next;l2 = l2.next;}if(l1 == null) l1 = headB;else l2 = headA;while(l1 != null && l2 != null){l1 = l1.next;l2 = l2.next;}if(l1 == null) l1 = headB;else l2 = headA;while(l1 != l2 && l1 != null && l2 != null){l1 = l1.next;l2 = l2.next;}return l1;// get length of headA and headB,//}
}
标答
public ListNode getIntersectionNode(ListNode headA, ListNode headB){if(headA == null || headB == null) return null;ListNode l1 = headA, l2 = headB;while(l1 != l2)(l1 = l1 == null ? headB : l1.next;l2 = l2 == null ? headA : l2.next;)return l1;
}