1、 给出两个单向链表的头指针pHead1和pHead2,判断这两个链表是否相交。假设两个链表均不带环。
示意图如下:
如果两个链表相交于某一节点,那么在这个相交节点之后的所有节点都是两个链表所共有的。也就是说,如果两个链表相交,那么最后一个节点肯定是共有的。先遍历第一个链表,记住最后一个节点,然后遍历第二个链表,到最后一个节点时和第一个链表的最后一个节点做比较,如果相同,则相交,否则不相交。时间复杂度为O( len1 + len2),因为只需要一个额外指针保存最后一个节点地址,空间复杂度为O(1)。(编程之美上面有详细的介绍)
http://blog.csdn.net/hackbuteer1/article/details/7583102
以下是代码验证了以下 略显粗糙:
typedef struct LNode
{
int value;
struct LNode* next;
}*Linklist,LNode;
Linklist Traverse(Linklist pt)
{
pt=pt->next;
while(pt->next)
{
cout<<pt->value<<" ";
pt=pt->next;
}
cout<<endl;
return pt;
}
int main()
{
std::vector<struct LNode> col(10);
std::vector<struct LNode>::iterator iter=col.begin();
int i=0;
for(;iter!=col.end();iter++)
{
iter->value=i++;
}
LNode begin1;
Linklist pt;
pt=&begin1;
begin1.next=&col[0];
col[0].next=&col[1];
col[1].next=&col[2];
col[2].next=&col[4];//col【2】为相交点
col[4].next=&col[7];
col[7].next=NULL;
LNode begin2;
Linklist pt2;
pt2=&begin2;
begin2.next=&col[3];
col[3].next=&col[6];
col[6].next=&col[2];
Linklist a=Traverse(pt);
Linklist b=Traverse(pt2);
if(a==b)
cout<<"the two insert together"<<endl;
return 0;
}