合并两个排序的链表JS

问题描述 投票:0回答:1
  1. 合并两个排序列表 给定两个已排序链表 list1 和 list2 的头。

将两个列表合并为一个排序列表。该清单应由 将前两个列表的节点拼接在一起。

返回合并链表的头。

https://leetcode.com/problems/merge-two-sorted-lists/description/

我正在尝试解决这个问题,但我不明白为什么我的逻辑或代码是错误的!!

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    let head = new ListNode()
    let temp = head
    while(list1 && list2){
        if(list1.val>list2.val){
            head.next = list2
            list2 = list2.next
        }
        if(list1.val <= list2.val){
            head.next = list1
            list1 = list1.next
        }
        head = head.next
    }
    if(list1){
        head.next = list1
    }
    if(list2){
        head.next = list2
    }
    return temp.next
};

我的测试用例是这样的:

谢谢你

javascript data-structures
1个回答
0
投票

这是我使用递归的代码:

    let curr = null;
let head = null;

var mergeTwoLists = function (list1, list2) {
  // base case to stop recursion at this stage
  if (!list1 && !list2) {
    let finalHead = head;
    head = null;
    curr = null;
    return finalHead;
  }

  // these will contain the next element of lists & will be passed in fn call
  let next1;
  let next2;

  // cases when one list ends before another
  if (!list1 && list2) {
    if (!head) {
      head = curr = list2;
    } else {
      curr.next = list2;
    }
    next2 = null;
  } else if (list1 && !list2) {
    if (!head) {
      head = curr = list1;
    } else {
      curr.next = list1;
    }
    next1 = null;
  }
  // normal use case where we compare values of curr ele of two lists
  else {
    if (list1.val <= list2.val) {
      if (!head) {
        head = curr = new ListNode(list1.val, null);
      } else {
        curr.next = new ListNode(list1.val, null);
        curr = curr.next;
      }
      next1 = list1.next;
      next2 = list2;
    } else {
      if (!head) {
        head = curr = new ListNode(list2.val, null);
      } else {
        curr.next = new ListNode(list2.val, null);
        curr = curr.next;
      }
      next2 = list2.next;
      next1 = list1;
    }
  }

  return mergeTwoLists(next1, next2);
};
© www.soinside.com 2019 - 2024. All rights reserved.