题目描述
输入两个链表,找出它们的第一个公共结点。
代码如下
//输入两个链表,找出它们的第一个公共结点。
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
void ListConstructor(ListNode* &pHead1, ListNode* &pHead2)
{
pHead1 = new ListNode(0);
pHead2 = new ListNode(10);
ListNode* pNode1 = pHead1;
ListNode* pNode2 = pHead2;
for(int i = 0; i < 10; i++)
{
ListNode* pTemp = new ListNode(i);
pNode1 -> next = pTemp;
pNode1 = pNode1 -> next;
}
for(int i = 15; i; i--)
{
ListNode* pTemp = new ListNode(i);
pNode2 -> next = pTemp;
pNode2 = pNode2 -> next;
}
pNode1 = pHead1;
pNode2 = pHead2;
while(pNode2->next && pNode1->next)
{
pNode1 = pNode1->next;
pNode2 = pNode2->next;
}
pNode1 ->next ? pNode2->next = pHead1 : pNode1->next = pHead2;
}
void ListDestructor(ListNode* &pHead1, ListNode* &pHead2)
{
ListNode* pNode1 = pHead1;
ListNode* pNode2 = pHead2;
while(pNode1)
{
pNode1 = pNode1->next;
delete pNode1;
}
while(pNode2)
{
pNode2 = pNode2->next;
delete pNode2;
}
}
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1 == NULL || pHead2 == NULL) return NULL;
ListNode* pNode1 = pHead1;
ListNode* pNode2 = pHead2;
int len1 = 0, len2 = 0, diff = 0;
while(pNode1)
{
len1++;
pNode1 = pNode1->next;
}
while(pNode2 != NULL)
{
len2++;
pNode2 = pNode2->next;
}
diff = abs(len1 - len2);
len1 > len2 ?
pNode1 = pHead1, pNode2 = pHead2 :
pNode1 = pHead2, pNode2 = pHead1 ;
for (int i = 0; i < diff; i++)
pNode1 = pNode1->next;
while(pNode1 && pNode2)
{
if(pNode1 == pNode2)
break;
pNode1 = pNode1->next;
pNode2 = pNode2->next;
}
return pNode1;
}
void PrintList(ListNode* &pHead1,ListNode* &pHead2)
{
ListNode* pNode1 = pHead1;
ListNode* pNode2 = pHead2;
cout << " pHead1:" << endl;
while (pNode1)
{
cout << pNode1->val<<endl;
pNode1 = pNode1->next;
}
cout << " pHead2:" << endl;
while(pNode2)
{
cout << pNode2->val << endl;
pNode2 = pNode2->next;
}
}
void FindFirstCommonNodeTest()
{
ListNode* pHead1,*pHead2;
ListConstructor(pHead1,pHead2);
PrintList(pHead1,pHead2);
ListNode* pFind = FindFirstCommonNode(pHead1,pHead2);
ListDestructor(pHead1,pHead2);
}