方法一:暴力
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {//先获得链表长度ListNode l1 = headA;ListNode l2 = headB;int m = 0, n = 0;while(l1 != null){m++;l1 = l1.next;}while(l2 != null){n++;l2 = l2.next;}ListNode l3 = headA;for(int i = 0; i < m; i++){ListNode l4 = headB;//l4定义放在第一层for循环中,避免第二层for循环结束后,出现nullpointerExceptionfor(int j = 0; j < n; j++){if(l3 == l4){return l3;} else {l4 = l4.next;}}l3 = l3.next;}return null;
}
方法二:
时间复杂度为O(n)
空间复杂度为O(1)
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {//先获得链表长度ListNode l1 = headA;ListNode l2 = headB;int m = 0, n = 0;while(l1 != null){m++;l1 = l1.next;}while(l2 != null){n++;l2 = l2.next;}//判断哪个链表短,将长的那个链表向后移动,直到和短的链表一样长。ListNode l3 = headA;ListNode l4 = headB;if(m < n){while(n-- != m){l4 = l4.next;}} else {while(m-- != n){l3 = l3.next;}}//再从这个节点开始判断两个链表的节点是否相等,判断下去while(l3 != l4){if(l3 == null){return null;}l3 = l3.next;l4 = l4.next;}return l3;
}
例图: