FastPrepMerge Two Sorted Linked Lists

Merge Two Sorted Linked Lists

ZS logoZS● EasyNEW GRADONSITE INTERVIEW

Updated

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]
listA
124
listB
134
return
112344
From listAFrom listB

Taking the smaller current head yields the merged ordering.

Example 2

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

Two empty lists produce an empty list.

Example 3

listA = []listB = [0]return = [0]
listA
empty
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 Onsite Interview questions

Similar questions at other companies

All ZS interview questionsSee ZS hiring insights
Saved
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode listA, ListNode listB) {
        // write your code here
    }
}
Checking account…