开始刷leetcode day10:Merge Two Sorted Lists

来源:互联网 发布:c js document.ready 编辑:程序博客网 时间:2024/05/16 01:00

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.


Java:

/**
 * 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) {
        if(l1 == null && l2 == null) return null;
        if(l1 == null || l2 == null) return l1==null?l2:l1;
        ListNode l3 = l1;
        ListNode l4 = l2;
        ListNode l6 = l3;
        ListNode head = l3;
        while(l3 != null && l4 != null)
        {
            if(l3.val <= l4.val)
            {
                l6 = l3;
                l3 = l3.next;
            }
            else if(l4.val < l3.val && l3 == l1 && l4 == l2) 
            {
                head = l4;
                l6 = head;
                l4 = l4.next;
                head.next = l3;
            }else   
            {
                ListNode newNode = new ListNode(l3.val);
                newNode.next = l3.next;
                l3.val = l4.val;
                l3.next = newNode;
                l4 = l4.next;
                l6 = l3;
                l3 = l3.next;
            }
            
        }
        
        ListNode l5 = l3 == null? l4:l3;
        if(l5 != null)
        {
            l6.next = l5;
        }
        
        return head;
    }
}

0 0