【LeetCode热题100】--160.相交链表

160.相交链表

【LeetCode热题100】--160.相交链表_第1张图片

使用双指针:

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

你可能感兴趣的:(LeetCode,leetcode,链表,算法)