Skip to content

Latest commit

 

History

History
135 lines (121 loc) · 2.71 KB

21.Merge Two Sorted Lists.md

File metadata and controls

135 lines (121 loc) · 2.71 KB
21.Merge Two Sorted Lists

easy

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

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
  function ListNode(val) {
      this.val = val;
      this.next = null;
  }

链表合并并排序,刚开始想的是 new 一个 node,然后通过对比,一个个插入,但是搞了许久卡主了。。。后来想到了递归法,瞬间清晰了许多

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    if(!l1) {
        return l2
    }
    if(!l2) {
        return l1
    }
    if (l1.val < l2.val) {
        l1.next = mergeTwoLists(l1.next, l2);
        return l1;
    }
    l2.next = mergeTwoLists(l1, l2.next);
    return l2;
};
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */
class Solution {
    func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        if(l1 == nil) {
            return l2
        }
        if(l2 == nil) {
            return l1
        }
        if(l1!.val < l2!.val) {
            l1!.next = mergeTwoLists(l1!.next, l2)
            return l1
        }
        l2!.next = mergeTwoLists(l1, l2!.next)
        return l2
    }
}

转念一想,我想写个不递归的:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    if(!l1) {
        return l2
    }
    if(!l2) {
        return l1
    }
    const head = new ListNode(null)
    let current = new ListNode(null)
    current = head
    while(l1 || l2) {
        if (!l1) {
            current.next = l2
            break
        }
        if (!l2) {
            current.next = l1
            break
        }
        if(l1.val < l2.val) { 
            const currentNode = new ListNode(l1.val)
            current.next = currentNode
            current = currentNode
            l1 = l1.next
        } else {
            const currentNode = new ListNode(l2.val)
            current.next = currentNode
            current = currentNode
            l2 = l2.next
        }
    }
    return head.next
};