Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagepy
themeEmacs
titleMerge Two Sorted Lists
linenumberstrue
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
    cur1 = l1
    cur2 = l2
    cur = None
    head = None

    if cur1 == None:
        return cur2
    elif cur2 == None:
        return cur1

    if cur1.val <= cur2.val:                    
        head = cur1
        cur = cur1
        cur1 = cur1.next
    else:
        head = cur2
        cur = cur2
        cur2 = cur2.next        
    
    while(cur1 != None or cur2 != None):
        # 한쪽이 끝이면 다른 쪽 값을 붙임
        if cur1 == None:
            cur.next = cur2
            return head
        elif cur2 == None:
            cur.next = cur1
            return head

        # 작은 값을 현재 값에 붙임
        if cur1.val <= cur2.val:
            cur.next = cur1
            cur = cur.next
            cur1 = cur1.next
        else:
            cur.next = cur2
            curcur2 = curcur2.next

        cur   cur2 = cur2cur.next

    return head