Skip to content

Latest commit

 

History

History
59 lines (50 loc) · 1.28 KB

0160. 相交链表.md

File metadata and controls

59 lines (50 loc) · 1.28 KB

160. 相交链表

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

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处


先计算长度,长的比短的长几步,就先走几步。然后两个一起走,直到找到相交。没有说明不相交。

注意写 while 条件时,不要遗漏第一个和最后一个。

/**
 * 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 currentA = headA, currentB = headB, lenA = 0, lenB = 0
  while(currentA.next) {
    currentA = currentA.next
    lenA ++
  }
  while(currentB.next) {
    currentB = currentB.next
    lenB ++
  }
  if (lenA > lenB) {
    for (let i = 0; i < lenA - lenB; i ++) {
      headA = headA.next
    }
  } else {
    for (let i = 0; i < lenB - lenA; i ++) {
      headB = headB.next
    }
  }
  while(headA) {
    if (headA === headB) {
      return headA
    }
    headA = headA.next
    headB = headB.next
  }
  return null
};