Scribbling

LeetCode: 24. Swap Nodes in Pairs 본문

Computer Science/Coding Test

LeetCode: 24. Swap Nodes in Pairs

focalpoint 2021. 8. 26. 20:18

< 25. Reverse Nodes in k-Group > 문제의 쉬운 version...

재귀를 이용해서 푸는 방법을 익혀두자.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        k = 2
        count, node = 0, head
        while node and count < k:
            node = node.next
            count += 1
        if count < k:
            return head
        new_head, prev = self.reverse(head, count)
        head.next = self.swapPairs(new_head)
        return prev

    def reverse(self, head, count):
        prev, cur, nxt = None, head, head
        while count > 0:
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt
            count -= 1
        return cur, prev