FastPrepMerge Two Sorted Linked Lists

Merge Two Sorted Linked Lists

Salesforce logoSalesforce● EasyNEW GRADPHONE SCREEN
Learn

Problem statement

Given the heads of two singly linked lists sorted in nondecreasing order, merge them into one list in nondecreasing order and return its head.

Reuse and relink the original nodes; keep every node exactly once. Both input lists are acyclic and share no nodes. Either list may be empty. When the current values are equal, take the node from list1 first; preserve the order within each input list.

The runner displays a linked list as its value sequence; an empty sequence represents a null head. For this exercise, assume the input lists satisfy the sorted and disjoint conditions and use the deterministic tie convention above.

Function

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

Examples

Example 1

list1 = [1,2,4]list2 = [1,3,4]return = [1,1,2,3,4,4]

Relink all original nodes in nondecreasing order, taking the first list first on a tie.

Example 2

list1 = []list2 = [0]return = [0]

Relink all original nodes in nondecreasing order, taking the first list first on a tie.

Example 3

list1 = []list2 = []return = []

Relink all original nodes in nondecreasing order, taking the first list first on a tie.

Constraints

  • 0 <= total number of nodes <= 100000.
  • -10^9 <= node.val <= 10^9.
  • Each input is sorted in nondecreasing order, acyclic and disjoint from the other input.

More Salesforce problems

See Salesforce hiring insights
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
    // Write your code here.
}
list1[1,2,4]
list2[1,3,4]
expected[1,1,2,3,4,4]
Checking account…