LeetCode160. 相交链表(Java)

题目:

编写一个程序,找到两个单链表相交的起始节点。
LeetCode160. 相交链表(Java)

示例:
LeetCode160. 相交链表(Java)LeetCode160. 相交链表(Java)
代码:

  • 解法一
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = 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) {
        if(headA==null&&headB==null){
            return null;
        }
        ListNode p1=headA;
        ListNode p2=headB;
        boolean p1Change=false;
        boolean p2Change=false;
        while(p1!=null&&p2!=null){
            if(p1==p2){
                return p1;
            }
            p1=p1.next;
            p2=p2.next;
            if(p1==null&&p1Change==true&&p2==null&&p2Change==true){
               break;
            }
            if(p1==null){
                p1=headB;
                p1Change=true;
            }
            if(p2==null){
                p2=headA; 
                p2Change=true;
            }
        }
        return null;
    }
}


解题思路:
LeetCode160. 相交链表(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 pA = headA, pB = headB;
        while(pA != pB){
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA: pB.next;
        }
        return pA;
    }
}