簡體   English   中英

查找兩個鏈表的交點的節點

[英]Finding node of intersection of two linked list

如何找到鏈表相交的節點?

     A1-->A2-->A3-->A4-->A5-->A6-->A7
                         ^
                         |
               B1-->B2-->B3
  1. A和B是兩個鏈接的鏈接列表
  2. A1,A2 ... A7和B1..B3是列表的節點
  3. 列表A和B在A5相交。

我們必須找到相交的節點

解決方案1:

對於列表中的每個節點,檢查下一個節點是否與另一個列表中的節點相同。

   if(A->next == B->next)
   {
      //nodes of interaction
   }

它的復雜度為m * n

解決方案2(高效):

  • 查找兩個列表的長度(分別為L1和L2)。
  • 找出長度[abs(L1-L2)]的絕對差。
  • 前往從先前的差異獲得的節點。
  • 現在開始檢查A-> next是否與B-> next相同
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int length1=0;
        int length2=0;

        ListNode head1 = headA;
        ListNode head2 = headB;
        while(headA!=null){
            length1++;
            headA = headA.next;
        }
        while(headB!=null){
            length2++;
            headB = headB.next;
        }
        int minus = length1-length2;
        int abs = Math.abs(minus);
        if(minus<0){
            int step=abs;
            while(step>0){
                head2 = head2.next;
                step--;
            }
        }else{
            int step=abs;
            while(step>0){
                head1 = head1.next;
                step--;
            }
        }
        if(head1==head2) 
          return head1;
        while(head1!=null&&head2!=null&&head1!=head2)
        {

              head1=head1.next;
              head2=head2.next;

        }
      return head1;  
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM