FastPrepMerge Two Sorted Linked Lists

Merge Two Sorted Linked Lists

ZS logoZS● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given the heads of two linked lists whose values are sorted in nondecreasing order, splice their existing nodes into one sorted list and return its head.

Duplicate values must be preserved. Either input list may be empty.

Function

mergeTwoLists(listA: ListNode, listB: ListNode) → ListNode

Examples

Example 1

listA = [1,2,4]listB = [1,3,4]return = [1,1,2,3,4,4]

Taking the smaller current head yields the merged ordering.

Example 2

listA = []listB = []return = []

Two empty lists produce an empty list.

Example 3

listA = []listB = [0]return = [0]

The nonempty list is returned.

Constraints

  • The two lists contain at most 50000 nodes in total.
  • Node values fit in a signed 32-bit integer.

More ZS problems

See ZS hiring insights
/** Definition for singly-linked list.
 * class ListNode { int val; ListNode next; }
 */
public ListNode mergeTwoLists(ListNode listA, ListNode listB) {
    // write your code here
}
listA[1,2,4]
listB[1,3,4]
expected[1,1,2,3,4,4]
Checking account…