首页 > 其他 > 详细

LeetCode每日一题2020.5

时间:2020-05-01 10:04:30      阅读:42      评论:0      收藏:0      [点我收藏+]

欢迎来访

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;
        }
    }
}

LeetCode每日一题2020.5

原文:https://www.cnblogs.com/optimjie/p/12812274.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!