FastPrepMerge Two Sorted Linked Lists

Merge Two Sorted Linked Lists

Apple logoApple● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

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

Relink the existing data nodes rather than copying their values into newly allocated data nodes. A temporary sentinel node is allowed. Preserve every duplicate. When equal heads are available, take the node from first before the node from second.

Each displayed list is its sequence of node values. An empty list represents a null head. Inputs contain no cycles or shared nodes.

Function

mergeSortedLists(first: ListNode, second: ListNode) → ListNode

Examples

Example 1

first = [1,2,4]second = [1,3,4]return = [1,1,2,3,4,4]

Each original node appears once in sorted order, including both ones and both fours.

Example 2

first = []second = [0]return = [0]

An empty first list leaves the second list unchanged.

Constraints

  • Each list contains between 0 and 10000 nodes.
  • -10^9 <= node.val <= 10^9.

More Apple problems

See Apple hiring insights
public ListNode mergeSortedLists(ListNode first, ListNode second) {
    // Write your solution here.
}
first[1,2,4]
second[1,3,4]
expected[1,1,2,3,4,4]
Checking account…