LeetCode 160 相交链表(Java实现)

题目描述:
题目描述


方法一(暴力法):

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

方法二(双指针):

假设链表A和链表B是相交于某点,p指向A的头部,q指向B的头部。首先,长链表+短链表 = 短链表+长链表,同时结合最后相交结点之后的距离是一样的,可以知道只要p遍历完A之后,遍历B,q遍历完B后,遍历A,这两个指针会在相交节点开始相遇,也就是找到相交节点的起始了。

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

结果:
结果

猜你喜欢

转载自blog.csdn.net/weixin_43752257/article/details/110622472