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.

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

https://leetcode.com/problems/intersection-of-two-linked-lists/

 1 package leetcode;
 2 public class Solution
 3 {
 4     public static ListNode getIntersectionNode(ListNode headA, ListNode headB)
 5     {
 6         int lenA=len(headA);
 7         int lenB=len(headB);
 8         while(lenA>lenB)
 9         {
10             headA=headA.next;
11             lenA--;
12         }
13         while(lenA<lenB)
14         {
15             headB=headB.next;
16             lenB--;
17         }
18         while(headA!=headB)
19         {
20             headA=headA.next;
21             headB=headB.next;
22         }
23         return headA;
24     }
25     public static int len(ListNode head)
26     {
27         int cout=0;
28         while(head!=null)
29         {
30             head=head.next;
31             cout++;
32         }
33         return cout;
34     }
35     public static void main(String args[])
36     {
37         ListNode a1=new ListNode(1);
38         ListNode a2=new ListNode(2);
39         ListNode a3=new ListNode(3);
40         ListNode b1=new ListNode(4);
41         ListNode b2=new ListNode(5);
42         ListNode c1=new ListNode(6);
43         ListNode c2=new ListNode(7);
44         ListNode headA=new ListNode(0);
45         ListNode headB=new ListNode(0);
46 
47         headA.next=a1;
48         a1.next=a2;
49         a2.next=a3;
50 //        a3.next=c1;
51         c1.next=c2;
52         headB.next=b1;
53         b1.next=b2;
54         b2.next=c1;
55 //        System.out.println(getIntersectionNode(headA,headB).val);
56     }
57 }
原文地址:https://www.cnblogs.com/qq1029579233/p/4403965.html