[LeetCode Hot 100] LeetCode160. 相交链表

发布时间 2023-12-03 11:40:00作者: Ac_c0mpany丶

题目描述


思路

方法一:

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

方法二:将方法一改写成三目运算符形式

/**
 * 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;
        ListNode q = headB;
        while (p != q) {
           p = (p != null) ? p.next : headB;
           q = (q != null) ? q.next : headA;
        }
        return p;
    }
}
// 三目运算符格式:
condition ? value_if_true : value_if_false

// 等价于

if (condition) {
    result = value_if_true;
} else {
    result = value_if_false;
}