思路:
如果两个链表相交,则在相交后的部分长度相等
例如:ListNode1 A -> B -> C -> D -> E-> G
ListNode2 H -> J -> D -> E -> G
上述两个节点在D节点相交,相交后的部分长度为3
ListNode1的长度为6
ListNode2的长度为5
长度相差1
此时将ListNode1从B节点开始遍历,即从头节点往后 1 个节点
ListNode2从头开始遍历
遍历到D节点时相等,找到相交节点
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
//单链表的实现
struct ListNode{
ListNode(int data=0):data(data),next(nullptr){};
int data;
ListNode *next;
};
class Clink{
public:
Clink(){
head = new ListNode();
}
~Clink(){
//节点的释放
}
public:
//链表的尾插法实现
void InsertTail(int val){
//先找到链表的尾节点
ListNode *p = head;
while(p->next!=nullptr){
p=p->next;
}
//生成新节点
ListNode *q = new ListNode(val);
p->next = q;
}
//链表的头插法
void InsertHead(int val){
//新建要插入的节点
ListNode *q = new ListNode(val);
//新建节点q指向头节点指向的next,
q->next = head->next;
//头节点指向新建节点
head->next = q;
}
void show(){
ListNode *p = head->next;
while(p!=nullptr){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
private:
ListNode *head;
ListNode *tail;
friend int main();
friend bool IsCross1(Clink *link1,Clink *link2,int &val);
};
//判断链表是否有环并且输出入口节点
bool IsCross0(ListNode *head1,ListNode *head2,int &val){
int cnt1=0,cnt2=0;
ListNode *p = head1->next;
ListNode *q = head2->next;
while(p!=nullptr){
p=p->next;
cnt1++;
}
while(q!=nullptr){
q=q->next;
cnt2++;
}
p = head1;
q = head2;
int offset = 0;
if(cnt1>cnt2){
offset = cnt1-cnt2;
while(offset-- >0){
p=p->next;
}
}else{
offset = cnt2-cnt1;
while(offset-- >0){
q=q->next;
}
}
while(p!=nullptr&&q!=nullptr){
if(q==p){
val = p->data;
cout<<"相交啦!节点值= "<<val<<endl;
return true;
}
p=p->next;
q=q->next;
}
return false;
}
bool IsCross1(Clink *link1,Clink *link2,int &val){
int cnt1=0,cnt2=0;
ListNode *p = link1->head;
ListNode *q = link2->head;
while(p!=nullptr){
p=p->next;
cnt1++;
}
while(q!=nullptr){
q=q->next;
cnt2++;
}
p = link1->head;
q = link2->head;
int offset = 0;
if(cnt1>cnt2){
offset = cnt1-cnt2;
while(offset-- >0){
p=p->next;
}
}else{
offset = cnt2-cnt1;
while(offset-- >0){
q=q->next;
}
}
while(p!=nullptr&&q!=nullptr){
if(q==p){
val = p->data;
cout<<"相交啦!节点值= "<<val<<endl;
return true;
}
p=p->next;
q=q->next;
}
return false;
}
int main(){
Clink link1;
Clink link2;
ListNode Node1;
ListNode Node2;
ListNode n1(1),n2(2),n3(3),n4(10),n5(12),n6(4);
Node1.next = &n1;
link1.head = &n1;
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
Node2.next = &n6;
n6.next = &n3;
int val = INT_MIN;
IsCross0(&Node1,&Node2,val);
link2.head = &n6;
n6.next = &n4;
IsCross1(&link1,&link2,val);
}