1、判断两个链表是否相交,若相交,求交点。(假设链表不带环)
两个指针同时指向两个链表,分别依次往后遍历链表到最后一个节点,如指针的值相同(即节点地址相同),反之没有交点。
int IsCross(Node* pHead1, Node* pHead2)
{Node* Node1 = pHead1;Node* Node2 = pHead2;if((NULL == pHead1) || (NULL == pHead2)){return 0;}while(Node1->next){Node1 = Node1->next;}while(Node2->next){Node2 = Node2->next;}if(Node1 == Node2){return 1;}else{return 0;}
}
求交点:先对两个链表做对齐处理,然后同时遍历,看节点地址是否相同,遇到第一个相同的节点即交点
Node* GetCrossNode(Node* pHead1, Node* pHead2)
{Node* Node = pHead1;int steps = 0;int len1 = Size(pHead1);int len2 = Size(pHead2);int result = IsCross(pHead1, pHead2);if(result == 0 || (NULL == pHead1) || (NULL == pHead2) ){return NULL;}if(len1 > len2)steps = len1-len2;elsesteps = len2-len1;Node = ( len1 > len2 ? pHead1:pHead2 );while ( steps-- ) //对齐处理{Node = Node->next;}len1> len2 ?( pHead1 = Node) : (pHead2 = Node);while ( pHead1 != pHead2 ){pHead1 = pHead1->next, pHead2 = pHead2->next;}return pHead1;
}
2、 判断两个链表是否相交,若相交,求交点。(假设链表可能带环)
1)环外相交:
2)环内相交:
判断是否相交:
int IsCrossWithCircle(Node* pHead1, Node* pHead2)
{Node* fast = pHead1;Node* slow = pHead2;while( fast && slow && fast != slow ){slow = slow->next;if(fast->next){fast=fast->next->next;}else{fast = fast->next;}}if(fast && slow && fast == slow)return 1;elsereturn 0;}
求交点:对于环内相交,环上所有的点相同,无交点;环外相交,就相当于不考虑带环的情况,参看上述方法