Algorithm/기본 알고리즘

leetcode 24. Swap Nods in Pairs

용자대디 2023. 1. 21. 15:38

def swap(head):
    dummy = ListNode(0)
    dummy.next = head
    prev, curr = dummy, head

    while curr and curr.next:
        ## save prt
        next_ptr = curr.next.next
        second = curr.next

        ## reverse
        second.next = curr
        curr.next = next_ptr
        prev.next = second

        ## update ptrs
        prev = curr
        curr = next_ptr
    return dummy.next

https://www.youtube.com/watch?v=o811TZLAWOo