Lumiere, and s5unnyjjj

[홀로 하는 코딩 공부] 012. Merge Two Sorted Lists(Python) 본문

Algorithm/Python

[홀로 하는 코딩 공부] 012. Merge Two Sorted Lists(Python)

s5unnyjjj 2024. 5. 27. 22:25
반응형

LeetCode

사용 언어: Python

문제 링크: https://leetcode.com/problems/merge-two-sorted-lists/

 

 

*** 본 문제를 푸는 과정을 공유하려 한다.


▶ 주어진 예제를 기준으로 보면, 입력이 들어오면 아래와 같이 출력되어야한다.(확실히 그림으로 그려보고나면 코드 방향성이 바로 생각난다.)

 

 

▶ 위의 그림을 보며 작성한 코드는 아래와 같다.

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        new_node = ListNode(0)

        cur_node = new_node

        while list1 and list2:
            if list1.val <= list2.val:
                cur_node.next = list1
                list1 = list1.next
            else:
                cur_node.next = list2
                list2 = list2.next
                
            cur_node = cur_node.next

        if list1 is not None:
            cur_node.next = list1
        if list2 is not None:
            cur_node.next = list2

        return new_node.next

 


>> 위 내용은 필자가 알고리즘 문제를 푼 코드입니다.

>> 부족한 점이 많을 수 있기에 잘못된 내용이나 궁금한 사항이 있으면 댓글 달아주시기 바랍니다.

>> 긴 글 읽어주셔서 감사합니다. 

반응형
Comments