티스토리 뷰

ALGORITHM/LeetCode

[leetcode] merge-two-sorted-lists.py

뚜비두빱 2021. 12. 26. 18:36
 

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

 

두개의 연결리스트를 하나로 합치는 문제 입니다.

이미 정렬이 되어있는 리스트 이기 때문에 두 연결리스트의 노드를 순회 하면서 둘중 더 작은 노드를  node.next 로 지정해서 나아가면 됩니다. get_next는 다음 노드를 정하는 함수 입니다. go_next는 노드 여부에 따라 진행할지 말지 정하는 함수입니다.

 

# https://leetcode.com/problems/merge-two-sorted-lists/
# merge-two-sorted-lists.py

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        
        def get_next(l1, l2):
            if l1 == None and l2 == None:
                return (None, None, None)
            if l1 == None:
                return (l2, l1, l2.next)
            elif l2 == None:
                return (l1, l1.next, l2)
            elif l1.val < l2.val:
                return (l1, l1.next, l2)
            else:
                return (l2, l1, l2.next)
        
        def go_next(node, l1, l2):
            next_node, l1, l2 = get_next(l1, l2)
            if l1 is None and l2 is None:
                if node is not None:
                    node.next = next_node
                return node
            node.next = go_next(next_node, l1, l2)
            return node
        next_node, l1, l2 = get_next(list1, list2)
        return go_next(next_node,l1, l2)

 

Discuss에 있는 간단한 코드:

개념은 비슷하지만.. 훨씬, 아주 간단하게 만들었다.

class Solution:
    def mergeTwoLists(self, a, b):
        if a and b:
            if a.val > b.val:
                a, b = b, a
            a.next = self.mergeTwoLists(a.next, b)
        return a or b

출처 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함