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.

答案


public class Solution {
    private int list_length(ListNode head) {
        int count = 0;
        while(head != null) {
            count++;
            head = head.next;
        }
        return count;
    }
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lengthA = list_length(headA);
        int lengthB = list_length(headB);
        //if(lengthA == 0 || lengthB == 0) return null;
        int diff = Math.abs(lengthA - lengthB);
        while(diff > 0) {
            headA = (lengthA > lengthB)? headA.next : headA;
            headB = (lengthB > lengthA)? headB.next : headB;
            diff--;
        }
        while(headA != null && headB != null) {
            if(headA == headB) return headA;
            headA = headA.next;
            headB = headB.next;
        }
        return null;

    }
}

第二次写这道题,更新下答案

public class Solution {
    public int listLen(ListNode head) {
        int len = 0;
        while(head != null) {
            head = head.next;
            len++;
        }
        return len;
    }
    
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = listLen(headA);
        int lenB = listLen(headB);
        if(lenA < lenB) return helper(headA, lenA, headB, lenB);
        return helper(headB, lenB, headA, lenA);
    }
    
    public ListNode helper(ListNode shorterList, int len1, ListNode longerList, int len2) {
        int diff = len2 - len1;
        while(longerList != null && shorterList != null) {
            if(shorterList == longerList) return shorterList;
            
            longerList = longerList.next;
            if(diff == 0) {
                shorterList = shorterList.next;
            }
            else {
                diff--;
            }
        }
        
        return null;
    }
}

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