21. 合并两个有序链表

原题链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode re = new ListNode();
        ListNode pvo = re;
        ListNode first = l1;
        ListNode second = l2;
        while (first != null && second != null){
            if (first.val < second.val){
                ListNode temp = new ListNode(first.val);
                first = first.next;
                pvo.next = temp;
            }else{
                ListNode temp = new ListNode(second.val);
                second = second.next;
                pvo.next = temp;
            }
            pvo = pvo.next; 
    }
    if (first != null){
        pvo.next = first;
    }
    if (second != null){
        pvo.next = second;
    }
    return re.next;
    }
}

 

posted on 2020-12-24 10:36  靠自己的骨头长肉  阅读(70)  评论(0编辑  收藏  举报