Problem Link: https://leetcode.com/problems/merge-two-sorted-lists/description/
Merge Two Sorted Lists - LeetCode
Can you solve this real interview question? Merge Two Sorted Lists - 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
leetcode.com
Solution 1. Two Pointers
Time: $O(N)$
Space: $O(1)$
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
head = ListNode(None); cur = None
while True:
if list1 is None and list2 is None:
return head.next
elif list1 is None:
if head.next is None:
head.next = list2
else:
cur.next = list2
return head.next
elif list2 is None:
if head.next is None:
head.next = list1
else:
cur.next = list1
return head.next
else:
if list1.val <= list2.val:
if head.next is None: # initial
head.next = list1
cur = list1
else:
cur.next = list1
cur = cur.next
list1 = list1.next
else:
if head.next is None: # initial
head.next = list2
cur = list2
else:
cur.next = list2
cur = cur.next
list2 = list2.next
return head.next
Solution 2. Recursion
Two pointer로 구현하니 코드가 너무 더러운 것 같아 재귀함수로 재구현하였다.
Time: $O(N)$
Space: $O(1)$
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
if list1 is None and list2 is None:
return None
elif list1 is None:
return list2
elif list2 is None:
return list1
else:
if list1.val <= list2.val:
list1.next = self.mergeTwoLists(list1.next, list2)
return list1
else:
list2.next = self.mergeTwoLists(list1, list2.next)
return list2