Problem Solving with Algorithms

반응형

leetcode.com/problems/add-two-numbers/

 

더미헤드를 하나 만들어서, 더미헤드의 다음부터 맨뒷자리 부터 더하고, 마지막에 캐리가 있으면 하나 더 추가해줌

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy_head = ListNode(0)
        curr = dummy_head
        carry = 0
        while l1 or l2:
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0
            sum = carry + x + y
            carry = sum // 10
            curr.next = ListNode(sum % 10)
            curr = curr.next
            
            if l1: l1 = l1.next
            if l2: l2 = l2.next
        if carry > 0:
            curr.next = ListNode(carry)
        return dummy_head.next

 

 

 

 

leetcode.com/problems/odd-even-linked-list/

class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        if not head:
            return None
        
        odd = head
        even = head.next
        even_head = even
        
        while even and even.next:
            odd.next = even.next
            odd = odd.next
            even.next = odd.next
            even = even.next
            
        odd.next = even_head
            
        return head

 

 

 

leetcode.com/problems/intersection-of-two-linked-lists/

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA and not headB:
            return None
        
        pa = headA
        pb = headB
        
        while pa != pb:
            pa = headB if not pa else pa.next
            pb = headA if not pb else pb.next
            
        return pa

 

반응형
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band