5/30/2014

19. Merge Two Sorted Lists

/**
 * 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) {
        if (l1==null) return l2;
        if (l2==null) return l1;
       
        ListNode p = new ListNode(0);
        p.next = l1;
        l1 = p;
        ListNode q = l2;
       
        while (q!=null) {
            if (p.next!=null) {
                if (q.val<p.next.val) {
                    ListNode temp;
                   
                    temp = p.next;
                    p.next = q;
                    q = q.next;
                    p.next.next = temp;
                } else p = p.next;
            } else {
                p.next = q;
                return l1.next;
            }
        }
       
        return l1.next;
    }
}

1 条评论: