【算法修炼-单链表】leetcode21. 合并两个有序链表(js)

121 阅读1分钟

题目链接:leetcode-cn.com/problems/me…

题目描述

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例1:

输入: l1 = [], l2 = []
输出: []

示例2:

输入: l1 = [1,2,4], l2 = [1,3,4]
输出: [1,1,2,3,4,4]

解题

思路: 新定义一个链表头,遍历两个链表,将小的值存到新链表中

/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    let mergeHead = new ListNode();
    let current = mergeHead;
    while (list1 && list2) {
        if (list1.val > list2.val) {
            current.next = list2;
            list2 = list2.next;
        } else {
            current.next = list1;
            list1 = list1.next;
        }
        current = current.next;
    }
    current.next = list1 || list2;
    return mergeHead.next;
};

总结

单链表最主要的是改变指针,不能丟指针。

算法修炼github:github.com/mengmengzp/…