您的位置 首页 JAVA(2017)

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;
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 21. Merge Two Sorted Lists》

发表评论

邮箱地址不会被公开。

返回顶部