LeetCode 21
Merge Two Sorted Lists
Concepts:
Linked List
Two Pointer
Description: You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Brute-force Approach
Extract the values of the two linked lists into arrays and merge them. Create a new linked list from that array for the result.
Time: O(n + m)
Space: O(n + m)
Optimal Approach
Iterate through the two linked lists, comparing the values of the nodes. Append the smaller node to the result list.
Time: O(n + m)
Space: O(1)