LeetCode 160 intersecting linked list (Java implementation)

Title description:
Title description


Method one (violence method):

/**
 * 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) {
    
    
        if(headA == null || headB == null){
    
    
            return null;
        }
        ListNode q,p;
        for(q = headA;q != null;q = q.next){
    
    
            for(p = headB;p != null;p = p.next){
    
    
                if(q == p){
    
    
                    return p;
                }
            }
        }
        return null;
    }
}

Method two (dual pointer):

Suppose that linked list A and linked list B intersect at a certain point, p points to the head of A, and q points to the head of B. First of all, long-linked list + short-linked list = short-linked list + long-linked list, combined with the same distance after the last intersecting node, we can know that as long as p traverses A, traverse B, q after traversing B, traverse A, these two The two pointers will start to meet at the intersection node, that is, the beginning of the intersection node is found.

/**
 * 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) {
    
    
        if(headA == null || headB == null){
    
    
            return null;
        }
        ListNode p = headA,q = headB;
        while(p != q){
    
    
            p = p == null ? headB : p.next;
            q = q == null ? headA : q.next;
        }
        return p;
    }
}

result:
result

Guess you like

Origin blog.csdn.net/weixin_43752257/article/details/110622472