您的位置:首页 > 其它

1.判断两个链表是否相交,若相交,求交点。(假设链表不带环)2.判断两个链表是否相交,若相交,求交点。(假设链表可能带环)【升级版】

2017-07-16 11:35 453 查看
//链表定义
typedef struct Node
{
Node(const int& value)
: m_value(value)
, m_pNext(NULL)
{}
int   m_value;
Node* m_pNext;
}Node, *pNode;
//判断链表是否相交 不带环
/*
算法思想:因为相交之后的部分长度是相等的,所以我们让长链表的长度减去
短链表的长度。然后让长链表开始走过相差的长度,与短链表同时向
后走。若指针相等,则链表相交;所走到NULL 则链表不相交
*/

int length(pNode pHead)
{
if (pHead == NULL)
return 0;
pNode node = pHead;
int count = 0;
while (node)
{
count++;
node = node->m_pNext;
}
return count;
}

pair<pNode, bool> isIntersect(pNode pHead1,pNode pHead2)
{
assert(pHead1&&pHead2);
pNode node1 = pHead1;
pNode node2 = pHead2;
int num = length(node1) - length(node2);
if (num > 0)
{
while (num--&&node1)
{
node1 = node1->m_pNext;
}
}
else if (num < 0)
{
int temp = abs(num);
while (temp--&&node2)
{
node2 = node2->m_pNext;
}
}
while (node1&&node2&&node1!=node2)
{
node1 = node1->m_pNext;
node2 = node2->m_pNext;
}
if (node1&&node2&&node1 == node2)
return make_pair(node1, true);
return make_pair(node1, false);
}

//链表是否相交 带环
pair<pNode, bool> MeetingPointInCirlec(pNode pHead1, pNode pHead2)
{
assert(pHead1&&pHead2);
if (!IsExistsLoop(pHead1).second
&&!IsExistsLoop(pHead2).second)//两个链表都不带环
return  isIntersect(pHead1, pHead2);
if ((IsExistsLoop(pHead1).second&&!IsExistsLoop(pHead2).second)
|| (!IsExistsLoop(pHead1).second && IsExistsLoop(pHead2).second))
//pHead1带环并且pHead2不带环或者pHead1不带环pHead2带环
return make_pair(pHead1, false);

//说明两个链表都带环,在其中一个链表的环内选取一个结点,遍历另
//一个链表如果有这个结点说明相交
pNode node = IsExistsLoop(pHead1).first;
pNode node2 = pHead2;
while (node->m_pNext!=node)
{
if (node->m_value == node2->m_value)
{
//相交环的入口点即是交点
pNode temp = FindLoopPort(pHead1);//求环的入口点
return make_pair(temp, true);
}
node = node->m_pNext;
node2 = node2->m_pNext;
}
return make_pair(node, false);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐