LeetCode每日一题2020.5

欢迎来访

2020.5.1 21. 合并两个有序链表

算法一:遍历

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode tail = dummy;
        ListNode p1 = l1, p2 = l2;
        while (p1 != null && p2 != null) {
            int val = 0;
            if (p1.val <= p2.val) {
                val = p1.val;
                p1 = p1.next;
            } else {
                val = p2.val;
                p2 = p2.next;
            }
            ListNode tmp = new ListNode(val);
            tail.next = tmp;
            tail = tmp;
        }
        tail.next = p1 == null ? p2 : p1;
        return dummy.next;
    }
}

算法二:递归

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        if (l1.val <= l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/optimjie/p/12812274.html