Merge Two Sorted Lists

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.

/**
 * 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 p1,p2;
        p1 = l1;
        p2 = l2;
        ListNode mergeHead;
        if (p1.val<p2.val) {
            mergeHead = p1;
            p1 = p1.next;
        } else {
            mergeHead = p2;
            p2 = p2.next;
        }
        ListNode p = mergeHead;
        while (p1!=null&&p2!=null) {
            if (p1.val<p2.val) {
                p.next = p1;
                p = p.next;
                p1 = p1.next;
            } else {
                p.next = p2;
                p = p.next;
                p2 = p2.next;
            }
        }
        if (p1!=null){
            p.next = p1;
        }
        if (p2!=null){
            p.next = p2;
        }
        return mergeHead;
    }
}

 

posted @ 2014-01-06 11:39  23lalala  阅读(110)  评论(0编辑  收藏  举报