力扣160 相交链表(双指针法+hash表法)

1.题目

在这里插入图片描述

2.自己初解的思路及问题:

看到题目后想到了双指针法,但是编写的代码逻辑有点问题,看一下题解后重写进行提交。

3.题解方法一:双指针法

public class Solution {
    
    
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    
    
        ListNode temp1 = headA;
        ListNode temp2 = headB;

        while(temp1 != temp2){
    
    
            temp1 = temp1 == null ? headB:temp1.next;
            temp2 = temp2 == null ? headA:temp2.next;
        }
        return temp1;
    }
}

以temp1 = temp1 == null ? headB:temp1.next;语句为例:
这边就是直接让headB或者temp1.next赋值给temp1,而不是让temp1指向他们,也很容易理解,因为后面只需要比较相遇的节点是否一致。这边注意一下这一点。

在这里插入图片描述

4.题解方法二:hash表法

遍历链表 A 并将每个结点的地址/引用存储在哈希表中。然后检查链表 B 中的每一个结点bi是否在哈希表中。若在,则 bi为相交结点。

根据思路自己直接写了代码:

public class Solution {
    
    
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    
    
        Set<ListNode> set =new HashSet<ListNode>();
        ListNode temp1 = headA;
        ListNode temp2 = headB;

        while(temp1 != null){
    
    
            set.add(temp1);
            temp1 = temp1.next;
        }
        while(temp2 != null){
    
    
            if(set.contains(temp2)){
    
    
                return temp2;
            }
            temp2 = temp2.next;
        }
        return null;
    }

}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ambitionLlll/article/details/113921612