[英]Finding node of intersection of two linked list
如何找到鏈表相交的節點?
A1-->A2-->A3-->A4-->A5-->A6-->A7
^
|
B1-->B2-->B3
我們必須找到相交的節點
解決方案1:
對於列表中的每個節點,檢查下一個節點是否與另一個列表中的節點相同。
if(A->next == B->next)
{
//nodes of interaction
}
它的復雜度為m * n
解決方案2(高效):
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.