You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a 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.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
Oops! I was stuck in my stupid mindset to merge one list to the other.
But the most direct way is to create a new list and just make it longer and longer!!!
Anyway, here is my stupid solution.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
head1,head2 = list1,list2
if head1 is None:
return head2
if head2 is None:
return head1
# ensure that list1 is the main list
if head1.val > head2.val:
head1,head2 = head2,head1
# initialize two pointers
p1,p2 = head1,head2
while not p1.next is None:
while not p2 is None:
# inner loop
if p1.next is None: # tail insert
p1.next = p2
return head1
elif p1.val <= p2.val <= p1.next.val: # mid insert
temp_p1_next = p1.next
temp_p2_next = p2.next
p1.next = p2
p2.next = temp_p1_next
p2 = temp_p2_next
head2 = p2
else:
p2 = p2.next
# outer loop, when p2 is None:
p2 = head2
p1 = p1.next
# tail insert
p1.next = p2
return head1
The time complexity is O ( n 2 ) O(n^2) O(n2) and the space complexity is O ( 1 ) O(1) O(1).
This is crazily complicated!!!
The step is as follow.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
# 1. create a empty list, and one pointer for each list.
# 2. compare the two nodes using pointers.
# 3. add the less one to the new list. add, move pointer, clear node next.
# 4. repeat 2 and 3
# 5. if pointer1 is None, pointer0 -> pointer2
# if pointer2 is None, pointer0 -> p0inter1
# 6. return head0
p0 = head0 = ListNode()
while list1 and list2:
if list1.val <= list2.val:
p0.next,p0, list1 = list1, list1, list1.next
else:
p0.next,p0, list2 = list2, list2, list2.next
p0.next = list1 if list1 else list2
return head0.next
Time complexity: O ( n ) O(n) O(n)
Space complexity: O ( 1 ) O(1) O(1)
本题思路不难,但是考验了如何处理链表的连接和断开,需要积累经验。
https://leetcode.com/problems/merge-two-sorted-lists/