LeetCode刷题之Merge Two Sorted Lists

Problem

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.

My Solution
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
  public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode p = l2;
        while (p != null) {
            if (l1 == null) {
                l1 = new ListNode(l2.val);
            } else {
                if (p.val < l1.val) {
                    ListNode q = new ListNode(p.val);
                    q.next = l1;
                    l1 = q;
                } else {
                    nodeInsert(l1, p.val);
                }
            }
            p = p.next;
        }
        return l1;
    }

    // 根据val的值在l链表中找到一个合适位置
    public void nodeInsert(ListNode l, int val) {
        ListNode p = l, q;
        // 如果待插入结点比头结点还要小,则直接作为头结点插入
        while (p.next != null && val > p.next.val) {
            p = p.next;
        }
        q = new ListNode(val);
        q.next = p.next;
        p.next = q;

    }
}
Great Solution
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        if(l1.val < l2.val){
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else{
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
}
    原文作者:Gandalf0
    原文地址: https://www.jianshu.com/p/7f0baaeefe39
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞