160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

 Notice
  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
Example

The following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

分析:

需要先得到两个List的长度,然后让长的List先走,等到长度一致的时候,比较两个指针是否指向同一个node,如果是,返回该node。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;      
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param headA: the first list
15      * @param headB: the second list
16      * @return: a ListNode 
17      * cnblogs.com/beiyeqingteng
18      */
19     public ListNode getIntersectionNode(ListNode h1, ListNode h2) {
20         if (h1 == null || h2 == null) return null;
21         
22         int size1 = size(h1);
23         int size2 = size(h2);
24         
25         for (int i = 0; i < Math.abs(size1 - size2); i++) {
26             if (size1 > size2) {            
27                 h1 = h1.next;
28             } else {
29                 h2 = h2.next;
30             }    
31         }
32         
33         while (h1 != h2) {
34             h1 = h1.next;
35             h2 = h2.next;
36         }
37         
38         return h1;
39     }
40     
41     private int size(ListNode head) {
42         int total = 0;
43         while (head != null) {
44             total++;
45             head = head.next;
46         }
47         return total;
48     }
49 }

转载请注明出处:cnblogs.com/beiyeqingteng/

posted @ 2016-07-03 02:12  北叶青藤  阅读(148)  评论(0编辑  收藏  举报