[leetcode - Bliend-75 ] 21. Merge Two Sorted Lists (Easy)

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

给两定两个 Linked-list list1list2 将两个 linked-list 合併,创建 res,比较 list1 和 list2 的 value 谁比较大,将比较小的 linked-list 接在 res 后面。

Coding

/** * 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 res = new ListNode(-1, null);    let cur = res;    while (list1 && list2) {        if (list1.val > list2.val) {            cur.next = list2;            list2 = list2.next;        } else {            cur.next = list1;            list1 = list1.next;        }        cur = cur.next;    }    cur.next = list1 || list2;    return res.next;};

http://img2.58codes.com/2024/wjmrn5I.gif

Time complexity: O(n)


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章