给出两个单向链表的头指针,判断两个链表是否相交。分为有环和没环两种情况:
1,没有环
方法一:对第一个链表哈希映射,建立哈希表,key为地址,value为值,然后遍历第二个链表的地址,看值是否一样。
方法二,既然相交,则最后一个节点肯定相同。
#include<iostream>
using namespace std;
struct ListNode{
int data;
ListNode* pNext;
};
void CreatList(ListNode* &pHead,int data)
{
ListNode* pNewNode = new ListNode();
pNewNode->data = data;
pNewNode->pNext = NULL;
if(NULL == pHead)
{
pHead = pNewNode;
}
else
{
ListNode* pNode = pHead;
while(pNode->pNext != NULL)
pNode = pNode->pNext;
pNode->pNext = pNewNode;
}
}
bool IsInterSect(ListNode* pHead1,ListNode* pHead2)
{
if(pHead1 == NULL || pHead2 == NULL)
return false;
else
{
ListNode* pNode1 = pHead1;
ListNode* pNode2 = pHead2;
while(pNode1->pNext != NULL)
pNode1 = pNode1->pNext;
while(pNode2->pNext != NULL)
pNode2 = pNode2->pNext;
if(pNode1->data == pNode2->data)
return true;
else
return false;
}
}
void DestoryList(ListNode* pHead)
{
ListNode* pNode = pHead;
ListNode* pNext = NULL;
while(pNode != NULL)
{
pNext = pNode->pNext;
delete pNode;
pNode = pNext;
}
pHead = NULL;
cout <<" 链表已被销毁!" << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
ListNode* pHead1 = NULL;
ListNode* pHead2 = NULL;
CreatList(pHead1,1);
CreatList(pHead1,2);
CreatList(pHead1,3);
CreatList(pHead1,6);
CreatList(pHead1,7);
CreatList(pHead2,4);
CreatList(pHead2,5);
CreatList(pHead2,6);
CreatList(pHead2,7);
cout << "是否相交:" << endl;
cout << IsInterSect(pHead1,pHead2) << endl;
DestoryList(pHead1);
DestoryList(pHead2);
system("pause");
return 0;
}