티스토리 뷰

반응형

# Definition for singly-linked list.  
# class ListNode:  
#     def \_\_init\_\_(self, val=0, next=None):  
#         self.val = val  
#         self.next = next  

class Solution:  
    def addTwoNumbers(self, l1: Optional\[ListNode\], l2: Optional\[ListNode\]) -> Optional\[ListNode\]:  
        result = ListNode()  
        head = result  
        append = 0  
        while l1 or l2 :  
            val = append  

            if l1 is not None:  
                val += l1.val  
            if l2 is not None:  
                val += l2.val  

            result.val = val % 10  
            append = val // 10  

            if l1 is not None:  
                l1 = l1.next  
            if l2 is not None:  
                l2 = l2.next  
            if l1 or l2:  
                result.next = ListNode()  
                result = result.next  



        if append:   
            n = ListNode()  
            n.val = append  
            n.next = None  
            result.next =  n  

        return head

깔끔하게 작성하기, 항상 어렵다. 지웠다 썼다가 한 2시간 걸린듯...

반응형