【Leetcode】160. Intersection of Two Linked Lists

於淼發表於2018-02-11

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.

Tips:找到兩個連結串列的第一個公共結點。

解題思路:先計算兩個連結串列的長度,將較長的連結串列即為node1.較短的記為node2.

計算兩個連結串列長度差為diff。讓node1先向前移動diff個結點,之後再讓兩個連結串列同時向後移動,直到到達兩個連結串列的公共結點。

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        int len1=getLength(headA);
        int len2=getLength(headB);
        ListNode node1=headA;
        ListNode node2=headB;
        //將長的賦值給1
        if(len1<len2){
            int temp=len1;
            len1=len2;
            len2=temp;
            node1=headB;
            node2=headA;
        }
        int diff=len1-len2;
        for(int i=0;i<diff;i++){
            node1=node1.next;
        }
        
        while(node1!=null && node2!=null && node1!=node2){
            node1=node1.next;
            node2=node2.next;
        }
        ListNode ans=new ListNode(0);
        if(node1==node2){
            ans=node1;
        }else{
            ans=null;
        }
        
        return ans;
    }
    private int getLength(ListNode head) {
        //計算連結串列長度
        ListNode node=head;
        int count=0;
        while(node!=null){
            node=node.next;
            count++;
        }
        return count;
    }

 

相關文章