Development/Algorithm
[LeetCode] Merge Two Sorted Lists
동스토리
2021. 8. 17. 21:26
반응형
안녕하세요.
LeetCode 21번 Merge Two Sorted Lists 문제풀이 하겠습니다.
https://leetcode.com/problems/merge-two-sorted-lists/
Merge Two Sorted Lists - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
[문제]
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
[TestCase]
[해설]
리스트 l1과 l2의 비교하여 순차적으로 새로운 리스트에 추가하는 방식
[코드]
# 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, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
if l2 is None:
return l1
if l1.val > l2.val:
head = ListNode(l2.val)
head.next = self.mergeTwoLists(l1, l2.next)
else:
head = ListNode(l1.val)
head.next = self.mergeTwoLists(l1.next, l2)
return head
감사합니다.
반응형