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

2020-11-20  本文已影响0人  BitterOutsider

题目描述

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

解题思路

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode n1 = l1;
        ListNode n2 = l2;
        ListNode resultNode = new ListNode(-1);
        ListNode result = resultNode;
        while (n1 != null || n2 != null) {
            if (n1 == null) {
                resultNode.next = n2;
                break;
            }
            if (n2 == null) {
                resultNode.next = n1;
                break;
            }
            if (n1.val > n2.val) {
                resultNode.next = n2;
                n2 = n2.next;
            } else {
                resultNode.next = n1;
                n1 = n1.next;
            }
            resultNode = resultNode.next;
        }
        return result.next;
    }
}
上一篇下一篇

猜你喜欢

热点阅读