🌗 160. 相交链表

吞佛童子2022年10月10日
  • algorithm
  • list
小于 1 分钟

🌗 160. 相交链表

难度: 🌗

问题描述

img_11.png


解法

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

输出

img_10.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou