输入两个链表,找出它们的第一个公共节点。

如下面的两个链表:

 

在节点 c1 开始相交。

 

 解法1

复制代码
/**
 * 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 len1=Solution.length(headA);
        int len2=Solution.length(headB);
        ListNode longList;
        ListNode shortList;
        int dis;
        if(len1>len2)
        {
            dis=len1-len2; 
            longList=headA;
            shortList=headB;
        }
        else
        {
            dis=len2-len1;
            longList=headB;
            shortList=headA;
          
        }
         while(dis!=0) 
         {
             longList=longList.next;
             dis--;

         }
              

        while(longList!=null)
        {
            if(longList==shortList)
                return longList;
            else
            {
                longList=longList.next;
                shortList=shortList.next;
            }
                
        }
        return null;
    }

    public static int length(ListNode listNode)
    {
        if(listNode==null) return 0;
        int sum=0;
        while(listNode!=null)
        {
            sum++;
            listNode=listNode.next;
            
        }
        return sum;
        
        
        
    }
}
复制代码

解法2

复制代码
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode A=pHead1;
        ListNode B=pHead2;
        while(A!=B)
        {
            A=A==null?pHead2:A.next;
            B=B==null?pHead1:B.next;
        }
        return A;
        
        
 
    }
    
  
}
复制代码

 

posted on   upupup-999  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!



点击右上角即可分享
微信分享提示