FastPrepMerge Two Sorted Lists

Merge Two Sorted Lists

IBM logoIBM● EasyFULLTIMEPHONE SCREEN

Problem statement

Given the heads of two singly linked lists, list1 and list2, return the head of one list containing all their values in nondecreasing order.

Each input list is already in nondecreasing order. Keep every occurrence of a repeated value. You may reuse input nodes or create new nodes; the returned value sequence is what matters.

An empty list is represented by []. If both lists are empty, return an empty list.

Function

mergeTwoLists(list1: ListNode, list2: ListNode) → ListNode

Examples

Example 1

list1 = [1,3,5]list2 = [1,2,6]return = [1,1,2,3,5,6]

The values from both lists in sorted order are [1, 1, 2, 3, 5, 6]. Both occurrences of 1 are kept.

Example 2

list1 = []list2 = [-2,0]return = [-2,0]

The first list is empty, so all values come from the second list in their existing order.

Constraints

  • Each list contains between 0 and 5000 nodes.
  • Each node value is between -10000 and 10000, inclusive.
  • Both lists are acyclic, are disjoint, and are in nondecreasing order.

More IBM problems

See IBM hiring insights
Saved
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
    // write your code here
}
list1[1,3,5]
list2[1,2,6]
expected[1,1,2,3,5,6]
Checking account…