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:

  1. If the two linked lists have no intersection at all, return null.
  2. The linked lists must retain their original structure after the function returns.
  3. You may assume there are no cycles anywhere in the entire linked structure.
  4. Your code should preferably run in O(n) time and use only O(1) memory.

思路

1)如果两个链表的某一个节点一样,那么说明两个链表有交点。
2)分别求出两个链表的长度,然后对长度长的链表向前移动:LenA - LenB,将两个链表进行对齐,之后一起遍历,直到找到第一个相同的节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        
        //1. get lenA and lenB
        ListNode head = headA;
        int lenA = 0;
        while (head != null) {
            lenA++;
            head = head.next;
        }
        
        int lenB = 0;
        head = headB;
        while (head != null) {
            lenB++;
            head = head.next;
        }
        
        //2. 对其2个链表
        if (lenA > lenB) {
            for (int i = 0; i < lenA - lenB; i++) {
                headA = headA.next;
            }
        } else {
            for (int i = 0; i < lenB - lenA; i++) {
                headB = headB.next;
            }
        }
        
        while (headA != null && headB != null) {
            if (headA.val == headB.val) return headA;
            else {
                headA = headA.next;
                headB = headB.next;
            }
        }
        return null;
    }
}

你可能感兴趣的:(160. Intersection of Two Linked Lists)