https://leetcode.com/problems/merge-two-sorted-lists/
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.
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
head = curr = ListNode()
while list1 and list2:
if list1.val < list2.val:
curr.next = list1
list1 = list1.next
else:
curr.next = list2
list2 = list2.next
curr = curr.next
if list1:
curr.next = list1
if list2:
curr.next = list2
return head.next
다른 사람의 재귀 방식 풀이이다. a에 합쳐지는 방식이며 b는 none이거나 크거나 같은 값을 가진다.
def mergeTwoLists(self, a, b):
if not a or b and a.val > b.val:
a, b = b, a
if a:
a.next = self.mergeTwoLists(a.next, b)
return a