Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

21. Merge Two Sorted Lists #4

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

新建一个头,while循环比较l1 l2大小

public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); ListNode flag = head;

    while(l1 != null || l2 != null) {
        if(l1 != null && l2 != null) {
            if(l1.val < l2.val) {
                flag.next = l1;
                l1 = l1.next;
            } else {
                flag.next = l2;
                l2 = l2.next;
            }
            flag = flag.next;
        } else if (l1 == null) {
            flag.next = l2;
            break;
        } else if (l2 == null) {
            flag.next = l1;
            break;
        }
    }
    return head.next;
}

}