LeeCode148相交链表(Java)(快慢指针或哈希)

题目链接:LeeCode148相交链表
题目描述:在这里插入图片描述
快慢指针:
计算两个数组的长度差,然后将较长数组的指针移动到与较短数组相等,然后一起走,相等时即为相交节点

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    
    
        ListNode slow=headA,fast=headB;
        //一起走,有一个停了就停下
        while(slow!=null&&fast!=null){
    
    
            slow=slow.next;
            fast=fast.next;
        }
        ListNode l,r;
        //判断谁是长的那个
        if(fast!=null){
    
    
            l=headB;
            r=headA;
            //根据长度差将较长的数组指针移到与短数组平齐
            while (fast!=null){
    
    
                l= l.next;
                fast=fast.next;
            }
        }else{
    
    
            l=headA;
            r=headB;
            while (slow!=null){
    
    
                l=l.next;
                slow=slow.next;
            }
        }
        //同一起点时,一起走,有相交的就返回
        while(l!=null&&r!=null){
    
    
            if(l==r)
                break;
            l=l.next;
            r=r.next;
        }
        return l;
    }
}

哈希:
每次将当前遍历的节点存起来,如果发现这个节点存过直接返回。

public class Solution {
    
    
   public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    
    
        Map<ListNode,Integer> map=new HashMap<>();
        while (headA != null && headB != null) {
    
    
            if(map.containsKey(headA)){
    
    
                return headA;
            }
            map.put(headA,headA.val);
            if(map.containsKey(headB)){
    
    
                return headB;
            }
            map.put(headB,headB.val);
            
            headA=headA.next;
            headB=headB.next;

        }
        while(headA!=null){
    
    
            if(map.containsKey(headA))return headA;
            headA=headA.next;
        }while(headB!=null){
    
    
            if(map.containsKey(headB))return headB;
            headB=headB.next;
        }
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43590593/article/details/113271242