题目描述:
编写程序判断两个单链表是否相交?
分析:我们知道对于单链表只有一个后继结点,因此如果两个单链表相交,那么它们的尾节点地址必定相同,因此,我们只需要判断尾节点是否相同即可。
typedef struct node* Node;
struct node
{
int val;
node *next;
};
bool isCrossList(Node nodeA,Node nodeB)
{
if(nodeA==nullptr||nodeB==nullptr)
return false;
Node headA=nodeA,headB=nodeB;
while(headA->next!=nullptr)
headA=headA->next;
while(headB->next!=nullptr)
headB=headB->next;
if(headA==headB)
return true;
else return false;
}