判断两个链表是否相交

假设两个链表的头指针分别为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

相关文章
相关标签/搜索