Linked Lists Combine Two Sorted

Languages

Given two linked lists, listA and listB, whose node values are in ascending order, combine both linked lists into a single sorted linked list and return the head node of the combined linked list.

The linked list is represented by a sequence of ListNodes, where each node points to the next node in the sequence, or null if it is the last node.

A ListNode has the following interface:

interface ListNode {
val: number;
next: ListNode | null;
}

Input

  • listA: ListNode | null: Head node of the first linked list, or null if the list is empty. Examples display each linked list as an array of values within the list
  • listB: ListNode | null: Head node of the second linked list, or null if the list is empty. Examples display each linked list as an array of values within the list

If both linked lists are empty, return null.

Examples

Input: listA = [-3,-1,9,10], listB = [-10,3,4,6,9]
Output: [-10,-3,-1,3,4,6,9,9,10]
Explanation: Combining the sorted lists [-3, -1, 9, 10] and [-10, 3, 4, 6, 9] results in a single sorted list [-10, -3, -1, 3, 4, 6, 9, 9, 10].
Input: listA = [1,2,4], listB = [1,3,4]
Output: [1,1,2,3,4,4]
Explanation: Combining the sorted lists [1, 2, 4] and [1, 3, 4] results in a single sorted list [1, 1, 2, 3, 4, 4].
Input: listA = [], listB = [0]
Output: [0]
Explanation: Combining the empty list [] with the sorted list [0] results in the list [0].

Constraints

  • 0 <= Number of nodes per list <= 50
  • -100 <= ListNode.val <= 100

Hints

New

Loading editor

    Linked Lists Combine Two Sorted | Algorithms Interview Questions with Solutions