160. Intersection of Two Linked Lists

题目分析

原题链接,登陆 LeetCode 后可用
这道题目是让我们判断两个链表有没有交叉点。其中比较特殊的情况有以下几种。

头结点相同(两指针刚开始就指向同一位置)
1 -> 2 -> 3
1 -> 3
没有交叉点(两指针同时到达尾部)
1 -> 2 -> 3
4 -> 6 -> 7
两链表至少有一个为空
null
null
// or
null
1 -> 2 -> 3
// or
1 ->2 -> 3
null

代码

/**
 * 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) {
        
        ListNode pA = headA;
        ListNode pB = headB;
        
        // 如果两个列表均为空
        if(pA == null || pB == null) {
            return null;
        }
        
        // 头结点相同
        if(pA == pB) {
            return pA;
        }
        
        while(pA.next != null && pB.next != null) {
            pA = pA.next;
            pB = pB.next;
            if(pA == pB) {
                return pA;
            }
        }
        
        // 同时到达尾结点
        if(pA.next == null && pB.next == null) {
            return null;
        }
        
        // pA 先到达尾结点
        if(pA.next == null) {
            pA = headB;
            pB = pB.next;
            while(pB.next != null) {
                pB = pB.next;
                pA = pA.next;
            }
            pB = headA;
            pA = pA.next;
        } else {  // pB 先到达尾结点
            pB = headA;
            pA = pA.next;
            while(pA.next != null) {
                pA = pA.next;
                pB = pB.next;
            }
            pA = headB;
            pB = pB.next;
        }
        
        if(pA == pB) {
            return pA;
        }
        while(pA.next != null && pB.next != null) {
            pA = pA.next;
            pB = pB.next;
            if(pA == pB) {
                return pA;
            }
        }
        return null;
    }
}

你可能感兴趣的:(160. Intersection of Two Linked Lists)