[LeetCode] 160. 相交链表

经典链表判断相交,记住就完事了。

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) {
        ListNode a = headA;
        ListNode b = headB;

        int cnt = 0;
        while (cnt <= 2) {
            if (a == b) return a;
            if (a == null) {
                a = headB;
                cnt++;
            } else {
                a = a.next;
            }
            if (b == null) {
                b = headA;
                cnt++;
            } else {
                b = b.next;
            }
        }

        return null;
    }
}
posted @ 2021-06-06 23:40  ACBingo  阅读(18)  评论(0编辑  收藏  举报