有環(huán)單鏈表相交判斷

如何判斷兩個(gè)有環(huán)單鏈表是否相交?相交的話返回true,不想交的話返回false。如果兩個(gè)鏈表長度分別為N和M,請做到時(shí)間復(fù)雜度O(N+M),額外空間復(fù)雜度O(1)。
給定兩個(gè)鏈表的頭結(jié)點(diǎn)head1head2(注意,另外兩個(gè)參數(shù)adjust0adjust1用于調(diào)整數(shù)據(jù),與本題求解無關(guān))。請返回一個(gè)bool值代表它們是否相交。

思路

兩個(gè)有環(huán)鏈表如果相交,只存在圖示三種情況.
所以首先我們都要找到兩個(gè)鏈表的入環(huán)節(jié)點(diǎn)entry1entry2.如果entry1==entry2,則屬于情況(1)或者(2),直接返回true即可.
否則從entry1或者entry2開始遍歷,繞環(huán)一圈,如果中途發(fā)現(xiàn)有等于另一個(gè)entry的點(diǎn),則說明屬于(3). 否則就是不相交的兩個(gè)有環(huán)鏈表.

有環(huán)鏈表相交的三種情況

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class ChkIntersection {
    public boolean chkInter(ListNode head1, ListNode head2, int adjust0, int adjust1) {
        ListNode entry1=findCycleEntry(head1);
        ListNode entry2=findCycleEntry(head2);
        if(entry1==entry2){
          return true;
        }
        else{
            ListNode backup=entry1;
            do{
                entry1=entry1.next;
            }while(entry1!=entry2&&entry1!=backup);
            return !(entry1==backup);
        }
    }
  
    
    //找到入環(huán)節(jié)點(diǎn)
    private ListNode findCycleEntry(ListNode head){
        if(head==null||head.next==null)return null;
        ListNode fast=head,slow=head;
        do{
            slow=slow.next;
            fast=fast.next.next;

        }while(slow!=fast&&fast.next!=null&&fast.next.next!=null);
        if(slow!=fast)return null;
        slow=head;
        while(slow!=fast){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
    }    
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容