题目描述
两个链表找相交的交点,输出地址 或者链表内元素
做法:
先判断两个链表否有交点,如果有交点,那他们最后面的节点一定是一样的 两个链表分别遍历 到最后面判断一下就好了。
接着就是类似 找lca步骤 先将两链表处于同一高度,移动len1-len2。接着一起往后平移即可。
时间复杂度O(n)
#include<bits/stdc++.h>
using namespace std;
struct node
{
int w;
node *next;
};
void print(node *head)
{
while(head!=NULL) {
printf("%d ",head->w);
head=head->next;
}
puts("");
}
bool check(node *head1,node *head2)
{
node *it1=head1,*it2=head2;
int len1=1,len2=1;
while(it1->next!=NULL) it1=it1->next,++len1;
while(it2->next!=NULL) it2=it2->next,++len2;
if(it1!=it2) return false;
// printf("%d %d\n",it1->w,it2->w);
// printf("len1:%d len2:%d\n",len1,len2);
if(len1>len2){
for(int i=1;i<=len1-len2;++i){
head1=head1->next;
}
}
else{
for(int i=1;i<=len2-len1;++i){
head2=head2->next;
}
}
while(head1!=NULL&&head2!=NULL)
{
if(head1==head2){
printf("交点 地址为:%d\n",head1);
return 1;
}
head1=head1->next;
head2=head2->next;
}
return 0;
//printf("-- %d %d\n",head1->w,head2->w);
}
int main()
{
node *head1,*head2,*tax;
node *p1,*p2,*p3;
head1=new node();
head2=new node();
tax=new node();
int n=3;
p1=head1;
while(n--)//构造第一个链表
{
node *ne=new node();
int x;
scanf("%d",&x);
ne->w=x;
head1->next=ne;
head1=head1->next;
}
p1=p1->next;
puts("**");
//print(p1);
n=5;
p2=head2;
while(n--)//构造第二个链表
{
node *ne=new node();
int x;
scanf("%d",&x);
ne->w=x;
head2->next=ne;
head2=head2->next;
}
p2=p2->next;
//print(p2);
n=4;
p3=tax;
while(n--)//构造共同交点的链表
{
node *ne=new node();
int x;
scanf("%d",&x);
ne->w=x;
tax->next=ne;
tax=tax->next;
}
p3=p3->next;
head1->next=p3;
head2->next=p3;
//print(p1);
//print(p2);
printf("%s",check(p1,p2)?"YES":"NO");
}
/*
1 2 3
4 5 6 7 8
9 10 11 12
*/