2014年5月11日星期日

Loop Solution - Merge Two Sorted Lists

Merge process for merge sort, key is the node.next = L to connect the new list.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(Integer.MIN_VALUE);
        ListNode node = head;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                node.next = l1;
                node = l1;
                l1 = l1.next;
            }else{
                node.next = l2;
                node = l2;
                l2 = l2.next;
            }
        }
        if(l1 != null){
            node.next = l1;
        }
        if(l2 != null){
            node.next = l2;
        }
       
        ListNode resHead = head.next;
        head.next = null;
       
        return resHead;
    }
}

没有评论: