美文网首页
Merge Two Sorted Lists

Merge Two Sorted Lists

作者: Wenyue_offer | 来源:发表于2017-09-14 02:11 被阅读0次
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        while(l1 != null && l2 != null)
        {
            if(l1.val < l2.val)
            {
                p.next = l1;
                p = p.next;
                l1 = l1.next;
            }
            else
            {
                p.next = l2;
                p = p.next;
                l2 = l2.next;
            }
        }
        if(l1 != null) p.next = l1;
        else p.next = l2;
        return dummy.next;
    }
}

相关文章

网友评论

      本文标题:Merge Two Sorted Lists

      本文链接:https://www.haomeiwen.com/subject/tcjrsxtx.html