LeetCode – 21. 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; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode curr1 = l1;
        ListNode curr2 = l2;
        ListNode res = new ListNode(0);
        ListNode currs = res;
        while(curr1 !=null || curr2 != null){
            if(curr1  == null){
                currs.next = curr2;
                currs = currs.next;
                curr2 = curr2.next;
                continue;
            }
            if(curr2  == null){
                currs.next = curr1;
                currs = currs.next;
                curr1 = curr1.next; 
                continue;
            }
            if(curr1.val < curr2.val){
                currs.next = curr1;
                currs = currs.next;
                curr1 = curr1.next;
            }
            else{
                currs.next = curr2;
                currs = currs.next;
                curr2 = curr2.next;
            }
        }
        currs.next = null;
        return res.next;
    }
}

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。