【JS】合并有序链表

合并有序链表

http://www.nowcoder.com/questionTerminal/a479a3f0c4554867b35356e0d57cf03d

非递归

/**
  * 
  * @param l1 ListNode类 
  * @param l2 ListNode类 
  * @return ListNode类
  */
function mergeTwoLists( l1 ,  l2 ) {
  let root = new ListNode(-1);
  let now = root;
  while (l1 || l2) {
    if (!l1 || !l2) {
      now.next = l1 ? l1 : l2;
      break;
    }
    if (l1.val > l2.val) {
      now.next = l2;
      l2 = l2.next;
    } else {
      now.next = l1;
      l1 = l1.next;
    }
    now = now.next;
  }
  return root.next;
}

递归

/**
  * 
  * @param l1 ListNode类 
  * @param l2 ListNode类 
  * @return ListNode类
  */
function mergeTwoLists( l1 ,  l2 ) {
  if (!l1 || !l2) return l1 ? l1 : l2;
  let res = null;
  if (l1.val > l2.val) {
    res = l2;
    res.next = mergeTwoLists(l1, l2.next);
  } else {
    res = l1;
    res.next = mergeTwoLists(l1.next, l2);
  }
  return res;
}

递归精简版

function mergeTwoLists( l1 ,  l2 ) {
  if (!l1 || !l2) return l1 ? l1 : l2;
  return l1.val > l2.val ? 
    ((l2.next = mergeTwoLists(l1, l2.next)) ? l2 : l2) : 
    ((l1.next = mergeTwoLists(l1.next, l2)) ? l1 : l1);
}
全部评论

相关推荐

评论
1
收藏
分享
牛客网
牛客企业服务