码迷,mamicode.com
首页 > 其他好文 > 详细

160. Intersection of Two Linked Lists

时间:2016-06-28 08:11:19      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

算出两个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     }

 

160. Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/warmland/p/5622095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!