160. Intersection of Two Linked Lists

算出两个list的长度,然后让长的那个往前移动长度差别。

这样两个list就是从同样长度的地方开始同时往后移动,如果两个头合在一起,或者到了linkedlist的尾部,就返回结果

 1     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 2         if(headA == null || headB == null) {
 3             return null;
 4         }
 5         int lenA = listLength(headA);
 6         int lenB = listLength(headB);
 7         int diff = 0;
 8         if(lenA > lenB) {
 9             diff = lenA - lenB;
10             while(diff-- > 0) {
11                 headA = headA.next;
12             }
13         } else {
14             diff = lenB - lenA;
15             while(diff-- > 0) {
16                 headB = headB.next;
17             }
18         }
19         while(headA != null) {
20             if(headA == headB) {
21                 return headA;
22             }
23             headA = headA.next;
24             headB = headB.next;
25         }
26         return null;
27     }
28     
29     private int listLength(ListNode head) {
30         int res = 0;
31         ListNode tempHead = head;
32         while(tempHead != null) {
33             tempHead = tempHead.next;
34             res++;
35         }
36         return res;
37     }

 

posted @ 2016-06-28 07:26  warmland  阅读(151)  评论(0编辑  收藏  举报