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) {
        ListNode p = null;
        ListNode h = new ListNode(0);//new一个头结点
        ListNode r = h;//尾指针
        while(l1!=null||l2!=null){
            //当l1所在链表遍历完成,直接将l2及l2的后继链表接入r的后面即可
            if(l1 == null){
                r.next = l2;
                return h.next;
            }
             //当l2所在链表遍历完成,直接将l1及l1的后继链表接入r的后面即可
            if(l2 == null){
                r.next = l1;
                return h.next;
            }
            //比较l1,l2所指节点的大小,选取较小的插入r后面
            if(l1.val<l2.val){
                p = l1;
                l1 = l1.next;
            }
            else{
                p = l2;
                l2 = l2.next;
            }
            r.next = p;
            r = p;
            r.next = null;
        }
        return h.next;
    }
}

 

posted @ 2015-02-03 16:06  mrpod2g  阅读(107)  评论(0编辑  收藏  举报