Leetcode-Intersection of Two Linked Lists

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

For example, the following two linked lists:

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

begin to intersect at node c1.

Notes:

    • 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.
    • Your code should preferably run in O(n) time and use only O(1) memory.

Solution:

 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     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
14         if (headA==null || headB==null) return null;
15 
16         ListNode s1 = headA;
17         ListNode s2 = headB;
18         int len1 = 1;
19         while (s1.next!=null){
20             len1++;
21             s1 = s1.next;
22         }
23         int len2 = 1;
24         while (s2.next!=null){
25             len2++;
26             s2=s2.next;
27         }
28         s1 = headA;
29         s2 = headB;
30         if (len1>len2){
31             while (len1>len2){
32                 s1 = s1.next;
33                 len1--;
34             }
35         } else if (len1<len2){
36             while (len1<len2){
37                 s2 = s2.next;
38                 len2--;
39             }
40         }
41 
42         while (s1!=null && s2!=null){
43             if (s1==s2)
44                 return s1;
45             s1 = s1.next;
46             s2 = s2.next;
47         }
48 
49         return null;
50     }
51 }
原文地址:https://www.cnblogs.com/lishiblog/p/4129761.html