160. 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.

含义:两个列表有交集,求出他们的交集开始点

方法一:

 1     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 2         ListNode a = headA;
 3         ListNode b = headB;
 4         //if a & b have different len, then we will stop the loop after second iteration
 5         while( a != b){
 6             //for the end of first iteration, we just reset the pointer to the head of another linkedlist
 7             a = a == null? headB : a.next;
 8             b = b == null? headA : b.next;
 9         }
10         return a; //如果a不等于null,代表找到了交集的开始点  如果a等于null,说明两个列表没有交集
11 }

方法二:

 1 private int getListLength(ListNode head) {
 2         int length = 0;
 3         while (head != null) {
 4             length++;
 5             head = head.next;
 6         }
 7         return length;
 8 }
 9 
10 public class Solution {
11     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
12         int lengthA = getListLength(headA);
13         int lengthB = getListLength(headB);
14         while (lengthA > lengthB) {
15             lengthA--;
16             headA = headA.next;
17         }
18         while (lengthB > lengthA) {
19             lengthB--;
20             headB = headB.next;
21         }
22         while (headA != headB) {
23             headA = headA.next;
24             headB = headB.next;
25         }
26         return headA; //如果headA不等于null,代表找到了交集的开始点  如果headA等于null,说明两个列表没有交集
27 }

方法三:解决方法就是将A链表尾节点指向头结点形成一个环,检测B链表是否存在环,如果存在,则两个链表相交,而检测出来的依赖环入口即为相交的第一个点

 1     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 2         if (headA == headB || headA==null) return headA;
 3         ListNode temp = headA;
 4         while (temp.next!=null) temp = temp.next;
 5         temp.next = headA;
 6         ListNode slow = headB,fast = headB;
 7         while (fast!=null && fast.next !=null)
 8         {
 9             slow = slow.next;
10             fast = fast.next.next;
11             if (slow == fast)
12             {
13                 while (headB != slow)
14                 {
15                     headB = headB.next;
16                     slow = slow.next;
17                 }
18                 return slow;
19             }
20 
21         }
22         return null;
23     }
原文地址:https://www.cnblogs.com/wzj4858/p/7728702.html