Skip to content

Latest commit

 

History

History
40 lines (33 loc) · 775 Bytes

160.md

File metadata and controls

40 lines (33 loc) · 775 Bytes

Leetcode 160. 相交链表

160. 相交链表

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function (headA, headB) {
  let a1 = headA;
  let b1 = headB;

  while (a1 !== b1) {
    if (a1 === null) {
      a1 = headB;// 链表 A 走完了,将 a1 指向 headB 继续遍历
    } else {
      a1 = a1.next;// 链表 A 一直往下走
    }

    if (b1 === null) {
      b1 = headA;// 链表 B 走完了,将 b1 指向 headA 继续遍历
    } else {
      b1 = b1.next;// 链表 B 一直往下走
    }
  }

  return a1;
};