[21.] LeetCode two merging sorted linked list

topic

Topic Portal: Portal (click here)
Here Insert Picture Description

answer

  1. The general idea of ​​it, two ListNode compare the size of the value, and then have the small one, the rest of the traverse turn back
  2. Until a ListNode is empty, it is added directly to a linked list of all of the two outer content
  3. To do so, the time complexity and space complexity are m + n
/**
 * 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 res = new ListNode(-1);
        ListNode temp = res;
        while (l1 != null && l2 != null) {
            ListNode node;
            if (l1.val > l2.val) {
                node = new ListNode(l2.val);
                l2 = l2.next;
            } else {
                node = new ListNode(l1.val);
                l1 = l1.next;
            }
            temp.next = node;
            temp = temp.next;
        }
        // 追加剩余的那个链表
        ListNode listNode = l1 == null ? l2 : l1;
        while (listNode != null) {
            temp.next = new ListNode(listNode.val);
            temp = temp.next;
            listNode = listNode.next;
        }
        return res.next;
    }
}
Published 138 original articles · won praise 148 · views 80000 +

Guess you like

Origin blog.csdn.net/qq1515312832/article/details/104345429