21. Merge Two Sorted Lists

kukudas·2022년 3월 3일
0

Algorithm

목록 보기
12/46
class Solution:
    def mergeTwoLists(self, list1, list2):
        result = None

        if not list1:
            return list2
        elif not list2:
            return list1
        elif not list1 and not list2:
            return result

        # 시작점 정해주기
        if list1 and list2:
            if list1.val > list2.val:
                result = list2
                list2 = list2.next
            else:
                result = list1
                list1 = list1.next

        # 리턴해줄헤드
        head = result

        # 둘다 남아 있을때
        while list1 and list2:
            if list1.val > list2.val:
                result.next = list2
                result = result.next
                list2 = list2.next
            # list1이 list2보다 같거나 작을때
            else:
                result.next = list1
                result = result.next
                list1 = list1.next


        # 리스트 중에 하나가 다 빠져서 하나만 남았을때
        if list1:
            result.next = list1
        else:
            result.next = list2

        return head

문제

0개의 댓글

관련 채용 정보