🌗 剑指 Offer 25. 合并两个排序的链表

吞佛童子2022年10月10日
  • algorithm
  • List
小于 1 分钟

🌗 剑指 Offer 25. 合并两个排序的链表

难度: 🌗

问题描述

img_21.png


解法

/**
 * 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;
        }
        ListNode res = new ListNode(-1);
        ListNode cur = res;
        ListNode a = l1;
        ListNode b = l2;
        while(a != null && b != null) {
            if(a.val <= b.val) {
                cur.next = new ListNode(a.val);
                a = a.next;
            } else {
                cur.next = new ListNode(b.val);
                b = b.next;
            }
            cur = cur.next;
        }
        if(a != null) {
            cur.next = a;
        } 
        if(b != null) {
            cur.next = b;
        }
        return res.next;
    }
}

输出

img_20.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou