[英]Intersection point of two linked lists
一個系統中有兩個單鏈表。 由於一些編程錯誤,其中一個鏈表的結束節點鏈接到了第二個鏈表,形成了一個倒 Y 形鏈表。 編寫一個程序來獲取兩個鏈表合並的點。
這是我的遞歸 function -
int intersection(Node* head_ref1 , Node* head_ref2){
Node* temp1 = head_ref1;
Node* temp2 = head_ref2;
if(temp1->next == temp2->next)
return temp1->data;
return intersection(temp1->next , temp2->next);
}
但它沒有給出正確的答案。 請解釋為什么我收到錯誤。
Node *outer_head = head_ref1;
while(outer_head -> next != null)
{
Node *inner_head = head_ref2;
while(inner_head -> next != null)
{
if(inner_head == outer_head)
{
//Here it is merging occured
}
inner_head = inner_head -> next;
}
outer_head = outer_head -> next;
}
復雜
O(n1 * n2)
解釋
外循環用於第一個鏈表的每個節點,內循環用於第二個鏈表。 在內部循環中,檢查第二個鏈表的任何節點是否與第一個鏈表的當前節點相同。
下面的代碼是 O(max(l1,l2)) 其中 l1 和 l2 是列表的長度。 如果您想比較迭代器而不是它們的值,請將 *itr1;=*itr2 更改為 itr1!=itr2;
auto itr1 = L1.rbegin(),last1=itr1;
auto itr2 = L2.rbegin(),last2=itr2;
for (; ++itr1 != L1.rend() && ++itr2 != L2.rend(); last1++, last2++) {
if (*itr1 != *itr2) break;
}
當它存在循環時,最后一個公共值是 *last1=*last2
編輯:我看到你有一個單鏈表。 在這種情況下,遍歷兩個列表並將元素或指針添加到每個堆棧,然后繼續彈出堆棧直到頂部不同
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.