美文网首页LeetCode
LeetCode刷题之Merge Two Sorted List

LeetCode刷题之Merge Two Sorted List

作者: JRTx | 来源:发表于2017-08-19 12:02 被阅读0次

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

    相关文章

      网友评论

        本文标题:LeetCode刷题之Merge Two Sorted List

        本文链接:https://www.haomeiwen.com/subject/qoltdxtx.html