/21. Merge Two Sorted Linked Lists

21. Merge Two Sorted Linked Lists

Easy
Linked Lists68% acceptance

Given the heads of two singly linked lists, each sorted in non-decreasing order, merge them into a single sorted linked list by rearranging their nodes. Return the head of the merged linked list.

Example 1

Input: head_a = ListNode(2, ListNode(5, ListNode(7))) head_b = ListNode(1, ListNode(3, ListNode(8)))

Output: [1,2,3,5,7,8]

Explanation: All nodes merged in sorted order.

Example 2

Input: head_a = None head_b = ListNode(4, ListNode(6))

Output: [4,6]

Explanation: Only head_b nodes present.

Example 3

Input: head_a = ListNode(-2) head_b = None

Output: [-2]

Explanation: Only head_a nodes present.

Constraints

  • 0 <= number of nodes in head_a <= 50
  • 0 <= number of nodes in head_b <= 50
  • -100 <= node value <= 100
  • Both head_a and head_b are sorted in non-decreasing order
Python (current runtime)

Case 1

Input: head_a = ListNode(-5, ListNode(0, ListNode(9))) head_b = ListNode(-3, ListNode(2, ListNode(10)))

Expected: [-5,-3,0,2,9,10]

Case 2

Input: head_a = None head_b = None

Expected: []

Case 3

Input: head_a = ListNode(1) head_b = ListNode(1)

Expected: [1,1]

Case 4

Input: head_a = ListNode(1, ListNode(2, ListNode(3))) head_b = ListNode(4, ListNode(5))

Expected: [1,2,3,4,5]