LeetCode-160. 相交链表

106 阅读1分钟

160. 相交链表

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