题目链接:链表相交
代码随想录思路链接:思路链接
注:相交点不在于所在节点值相等而在于其地址相等
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
int lenA=0,lenB=0;
struct ListNode *A=headA;
struct ListNode *B=headB;
while(A)
{
lenA++;
A=A->next;
}
while(B)
{
lenB++;
B=B->next;
}
A=headA;
B=headB;
if(lenA>lenB)
{
int len=lenA-lenB;
while(len)
{
A=A->next;
len--;
}
while(A)
{
if(A==B)
{
return A;
}else
{
A=A->next;
B=B->next;
}
}
}else{
int len=lenB-lenA;
while(len)
{
B=B->next;
len--;
}
while(B)
{
if(A==B)
{
return B;
}else
{
A=A->next;
B=B->next;
}
}
}
return NULL;
}
java解法:寻找链表交点找到的不是结点值相等而是链表的地址相等
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA=0,lenB=0;
ListNode p,q;
p=headA;
q=headB;
while(p!=null)
{
lenA++;
p=p.next;
}
while(q!=null)
{
lenB++;
q=q.next;
}
p=headA;
q=headB;
if(lenA<lenB)
{
int t;
t=lenA;
lenA=lenB;
lenB=t;
ListNode temp;
temp=p;
p=q;
q=temp;
}
int gap=lenA-lenB;
while(gap>0)
{
p=p.next;
gap--;
}
while(p!=null)
{
if(p==q)
{
return p;
}
p=p.next;
q=q.next;
}
return null;
}
}