判斷兩個鏈表是否相交

假設兩個鏈表的頭指針分別爲h1,h2編程

  • 思路一指針

    將h1的尾節點的指針域指向h2的頭結點,即將h2鏈接在h1的後面。若是兩個鏈表相交,那麼此時的h2確定是個循環鏈表,不然仍是一個單向鏈表。此時的問題就簡化成判斷此時的h2是否爲循環鏈表。code

 

代碼實現class

bool isIntersect(pNode h1, pNode h2)
{

	if(!h1 || !h2)
		return false;
	
	bool flag = false;
	pNode temp_h1 = h1;
	pNode temp_h2 = h2;

	//找到第一個鏈表的尾節點,將第二個鏈表掛在其後
	while(temp_h1->next != NULL)
		temp_h1 = temp_h1->next;
	temp_h1->next = h2;

	do 
	{
		temp_h2 = temp_h2->next;
	}while(temp_h2 && temp_h2 != h2);

	if(temp_h2 == h2)
		flag = true;

	//將鏈表恢復原樣
	temp_h1->next = NULL;
	
	return flag;
}
  • 思路二書籍

    若是兩個單向鏈表相交,那麼這兩個鏈表的尾結點必定相同(地址相同)。循環

代碼實現鏈表

bool isIntersect(pNode h1, pNode h2)
{

	if(!h1 || !h2)
		return false;
	
	pNode tail_h1 = h1;
	pNode tail_h2 = h2;

	while(tail_h1->next != NULL)
		tail_h1 = tail_h1->next;

	while(tail_h2->next != NULL)
		tail_h2 = tail_h2->next;

	if(tail_h1 == tail_h2)
		return true;
	return false;
}

 

參考書籍:《編程之美》next

相關文章
相關標籤/搜索