給定兩個單向鏈表,找出它們的第一個公共節點。節點定義如下:
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
};
在第一條鏈表上逐個遍歷,每取一個節點就到第二條鏈表上從頭掃一遍,一旦找到同一個節點(比較的是位址而非值)就说明兩表在此重合。方法直白,但時間複雜度是 O(m×n),實戰中通常不取。
關鍵在於:兩條鏈表一旦相交,之後的節點必然完全共用,形成 Y 字形。因此只要讓兩個指標同步前進,第一次相遇處就是答案。
時間複雜度 O(m+n),額外空間 O(1)。
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
};
ListNode* CreateListNode(int value)
{
ListNode* pNode = new ListNode();
pNode->m_nValue = value;
pNode->m_pNext = NULL;
return pNode;
}
void ConnectListNodes(ListNode* pCurrent, ListNode* pNext)
{
if (pCurrent == NULL)
{
printf("Error to connect two nodes.\n");
exit(1);
}
pCurrent->m_pNext = pNext;
}
void PrintList(ListNode* pHead)
{
printf("PrintList starts.\n");
ListNode* pNode = pHead;
while (pNode != NULL)
{
printf("%d\t", pNode->m_nValue);
pNode = pNode->m_pNext;
}
printf("\nPrintList end.\n");
}
void DestroyList(ListNode* pHead)
{
ListNode* pNode = pHead;
while (pNode != NULL)
{
pHead = pHead->m_pNext;
delete pNode;
pNode = pHead;
}
}
unsigned int GetListLength(ListNode* pHead)
{
unsigned int nLength = 0;
ListNode* pNode = pHead;
while (pNode != NULL)
{
++nLength;
pNode = pNode->m_pNext;
}
return nLength;
}
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2)
{
unsigned int nLength1 = GetListLength(pHead1);
unsigned int nLength2 = GetListLength(pHead2);
int nLengthDif = nLength1 - nLength2;
ListNode* pListHeadLong = pHead1;
ListNode* pListHeadShort = pHead2;
if (nLength2 > nLength1)
{
pListHeadLong = pHead2;
pListHeadShort = pHead1;
nLengthDif = nLength2 - nLength1;
}
// 長鏈表先走幾步
for (int i = 0; i < nLengthDif; ++i)
pListHeadLong = pListHeadLong->m_pNext;
// 同步前進
while ((pListHeadLong != NULL) &&
(pListHeadShort != NULL) &&
(pListHeadLong != pListHeadShort))
{
pListHeadLong = pListHeadLong->m_pNext;
pListHeadShort = pListHeadShort->m_pNext;
}
return pListHeadLong;
}
// 第一個公共節點在鏈表中央
// 1 - 2 - 3 \
// 6 - 7
// 4 - 5 /
int main()
{
ListNode* pNode1 = CreateListNode(1);
ListNode* pNode2 = CreateListNode(2);
ListNode* pNode3 = CreateListNode(3);
ListNode* pNode4 = CreateListNode(4);
ListNode* pNode5 = CreateListNode(5);
ListNode* pNode6 = CreateListNode(6);
ListNode* pNode7 = CreateListNode(7);
ConnectListNodes(pNode1, pNode2);
ConnectListNodes(pNode2, pNode3);
ConnectListNodes(pNode3, pNode6);
ConnectListNodes(pNode4, pNode5);
ConnectListNodes(pNode5, pNode6);
ConnectListNodes(pNode6, pNode7);
ListNode* pResult = FindFirstCommonNode(pNode1, pNode4);
printf("%d\n", pResult->m_nValue);
return 0;
}