# 21 Merge Sorted List

input是兩個linked list, l1和l2, output是把l1和l2組合起來並排序。

Concept:

Concept:
Create a ListNode head to save the result
ListNode ptr = head
while either l1 or l2 still have node left
    if l1!=null && l1 <= l2
        ptr.next = l1
        ptr = ptr.next
        l1 = l1.next
    if l2 != null && l2 < l1
        ptr.next = l2
        ptr = ptr.next
        l2 = l2.next

return head.next

完整程式碼:

/**
 * 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 head = new ListNode(0);
        ListNode ptr = head;

        while(l1!=null && l2!=null){
            if(l1.val<=l2.val){
                ptr.next = l1;
                ptr = ptr.next;
                l1 = l1.next;
            }
            else{
                ptr.next = l2;
                ptr = ptr.next;
                l2 = l2.next;
            }
        }
        if(l1==null)
            ptr.next = l2;
        if(l2==null)
            ptr.next = l1;

        return head.next;
    }
}

results matching ""

    No results matching ""