从第一个公共结点开始,之后它们所有结点都是重合的,不可能再出现分叉。
分析:
方法一:分别把两个链表的结点放入两个栈中,这样两个链表的尾结点就位于两个栈的栈顶,然后比较两个栈顶的结点是否相同。若相同,则把栈顶弹出接着比较下一个栈顶,直到找到最后一个相同的结点。
空间复杂度:O(n1+n2), 因为需要两个辅助栈。时间复杂度:O(n1+n2)
方法二:首先遍历两个链表得到他们的长度,在第二次遍历时,在较长的链表上先走若干步,接着再同时在两个链表上遍历,找到第一个相同的结点就是他们的第一个公共结点。
时间复杂度:O(n1+n2), 不需要额外的辅助空间。
#include "stdafx.h"
#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(pHead == NULL)
{
pHead = pNewNode;
}
else
{
ListNode* pNode = pHead;
while(pNode->pNext != NULL)
pNode = pNode->pNext;
pNode->pNext = pNewNode;
}
}
void DestoryList(ListNode* pHead)
{
ListNode* pNode = pHead;
ListNode* pNext = NULL;
while(pNode != NULL)
{
pNext = pNode->pNext;
delete pNode;
pNode = pNext;
}
pHead = NULL;
cout <<" 链表已被销毁!" << endl;
}
unsigned int GetListLen(ListNode* pHead)
{
ListNode* pNode = pHead;
unsigned int len = 0;
while(pNode != NULL)
{
pNode = pNode->pNext;
len ++;
}
return len;
}
int FindTheCommonSameNode(ListNode* pHead1,ListNode* pHead2)
{
unsigned int len1 = GetListLen(pHead1);
unsigned int len2 = GetListLen(pHead2);
int k = len1 - len2;
ListNode* pLong = pHead1;
ListNode* pShort = pHead2;
if(len1 < len2)
{
pLong = pHead2;
pShort = pHead1;
k = len2 - len1;
}
//现在长链表走k步
for(int i = 0;i < k;++i)
pLong = pLong->pNext;
while((pLong != NULL) && (pShort != NULL) && (pLong->data != pShort->data))
{
pLong = pLong->pNext;
pShort = pShort->pNext;
}
return pLong->data;
}
int _tmain(int argc, _TCHAR* argv[])
{
ListNode* pHead1 = NULL;
ListNode* pHead2 = NULL;
int num = 0;
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 << FindTheCommonSameNode(pHead1,pHead2) << endl;
DestoryList(pHead1);
DestoryList(pHead2);
system("pause");
return 0;
}