Java-160.相交链表【力扣】

编写一个程序,找到两个单链表相交的起始节点。

如下面的两个链表:
在这里插入图片描述

在节点c1开始相交。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
解题思路:
注意:链表只能Y型相交,不能X型相交
比较cur1(a1)和cur2(b1)是否是相同的节点(不是比较节点的数值,是比较节点的内存地址)
if(cur1==cur2)
引用本质上就是指针(存了一个地址这样的证书),就是在比较cur1所在的内存地址和cur2所在的内存地址是不是同一个地址。
依次进行比较,如果cur1和cur2都已经到达null还没有重合,就意味着链表不相交。
如果两个链表的长度不一样:
可以先求出两个链表的长度,做差offset,让链表长的先走offset步,然后再让两个cur同时走。

代码实现:

public class Solution{
    
    
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    
    
   //1、分别求出两个链表的长度
   int size1=size(headA);
   int size2=size(headB);
   //2、算出差值,让长的链表先走
   if(size1>size2) {
    
    
    int offset =size1-size2;
    for(int i=0;i<offset;i++) {
    
    
     headA=headA.next;
    }
   }else {
    
    
    int offset=size2-size1;
    for(int i=0;i<offset;i++) {
    
    
     headB=headB.next;
    }
   }
   //3、此时headA和headB已经在同一起跑线了,可以开始比较节点的身份了
   while(headA!=null&&headB!=null) {
    
    
    if(headA==headB) {
    
    
     //是相同节点,这个位置就是链表的交点
     return headA;
    }
    headA=headA.next;
    headB=headB.next;
   }
   return null;
   //没有相交节点
  }
  public int size(ListNode head) {
    
    
    int size=0;
    ListNode cur=head;
    while(cur!=null) {
    
    
     size++;
     cur=cur.next;
    }
    return size;
   }
 }

猜你喜欢

转载自blog.csdn.net/weixin_44378053/article/details/105637038