iT邦幫忙

0

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

  • 分享至 

  • xImage
  •  

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;
};

https://i.imgur.com/wjmrn5I.gif

Time complexity: O(n)


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言