Likou 160 intersecting linked list (double pointer method + hash table method)

1. Title

Insert picture description here

2. My initial thoughts and problems:

After seeing the title, I thought of the double pointer method, but the logic of the written code was a bit problematic. After looking at the solution, rewrite it and submit it.

3. Problem solving method 1: double pointer method

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;
    }
}

Take the temp1 = temp1 == null? HeadB:temp1.next; statement as an example:
here is to directly assign headB or temp1.next to temp1 instead of letting temp1 point to them. It is also easy to understand, because you only need to compare encounters later. Whether the nodes are the same. Pay attention to this here.

Insert picture description here

4. Problem solving method 2: hash table method

Traverse the linked list A and store the address/reference of each node in the hash table. Then check whether each node bi in the linked list B is in the hash table. If it is, then bi is the intersection node.

According to the idea, I wrote the code directly:

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;
    }

}

Insert picture description here

Guess you like

Origin blog.csdn.net/ambitionLlll/article/details/113921612