首页 > 代码库 > leetcode 160. Intersection of Two Linked Lists --------- java

leetcode 160. Intersection of Two Linked Lists --------- java

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.

 

直接上代码,比较简单。

 

/**
 * 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) {
        int len1 = 1,len2 = 1;
        if( headA == null || headB == null)
            return null;
        ListNode node1 = headA;
        ListNode node2 = headB;
        
        while( node1.next != null ){
            node1 = node1.next;
            len1++;
        }
        while( node2.next != null ){
            node2 = node2.next;
            len2++;
        }
        if( len1 == 0 || len2 == 0 || node1 != node2 )
            return null;
        node1 = headA;
        node2 = headB;
        if( len1 > len2 ){
            while( len1 > len2 ){
                len1--;
                node1 = node1.next;
            }
        }else if( len1 < len2 ){
            while( len1<len2){
                len2--;
                node2 = node2.next;
            }
        }

        while( len1 >0 ){
            if( node1 == node2 )
                return node1;
            node1 = node1.next;
            node2 = node2.next;
            len1--;
        }
        return null;
    }
}

 

leetcode 160. Intersection of Two Linked Lists --------- java