21. 合并两个有序链表 JavaScript实现

69 阅读2分钟

21. 合并两个有序链表

合并有序链表

一、递归

递归详解 在这里插入图片描述

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
var mergeTwoLists = function(list1, list2) {
    // 进行判空的处理
    if(list1 == null) return list2;
    if(list2 == null) return list1;
    
    // 进行值的比较
    if (list1.val <= list2.val){
        list1.next = mergeTwoLists(list1.next,list2);
        return list1;
    }else{
        list2.next = mergeTwoLists(list1,list2.next);
        return list2;
    }
};

二、迭代 -- 哨兵节点

1、哨兵节点

哨兵节点的作用是方便得到最后的链表,即一个虚拟的头节点。

2、迭代的过程

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
var mergeTwoLists = function(list1, list2) {
    // 设置哨兵节点(虚拟头节点),将较小的节点连接到这个哨兵节点,最后返回prehead.next即可。
    let preHead = new ListNode(-1);
    
    // 设置一个pre指针,用于连接链表 
    let pre = preHead;
    
    
    // 开始遍历,比较两者大小。当两个链表均不空的时候,进行值的比较
    while(list1 && list2){
        if(list1.val <= list2.val){
            pre.next = list1;
            list1 = list1.next;
        }else{
            pre.next = list2;
            list2 = list2.next;
        }
        
        // 移动pre的指针
        pre = pre.next;
    }
    
    // 当一开始其中一个链表为空的时候,或者一直遍历直到其中一个短的链表为空的时候,直接把非空的另外一个链表添加到pre.next
    if (list1 == null){
        pre.next = list2;
    }else{
        pre.next = list1;
    }
    
    return preHead.next;

};

三、js语法

1、undefine null Null

(1) null \ Null

Null是数据类型,null是空值。

// 某个值是否为空的判断,用null
while(list1 == null){
}

while(list1 != null){
}

while(list1){
}

(2)undefined \ not defined \ null

  • null表示“没有对象”,即此处不该有值.
  • undefined表示"缺少值",就是此处应该有一个值,但是还没有定义。
// undefined 一个定义了但是未赋值的变量
var a;
console.log(a);

// not defined 一个未定义的没有声明的对象
console.log(a);
 

2、创建新的节点

// 定义节点
function ListNode(val, next) {
     this.val = (val===undefined ? 0 : val)
     this.next = (next===undefined ? null : next)
}

// 创建新的节点 -- new
let preHead = new ListNode(-1);

3、递归的调用

直接在里面调用即可

var mergeTwoLists = function(list1, list2) {
	list1.next =  mergeTwoLists(list1.next,list2);
};