LeetCode 24. Swap Nodes in Pairs

개발공부를해보자·2025년 1월 12일

LeetCode

목록 보기
17/95

파이썬 알고리즘 인터뷰 문제 17번(리트코드 24번) Swap Nodes in Pairs
https://leetcode.com/problems/swap-nodes-in-pairs/

나의 풀이1(재귀)

# 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]:
        
        def helper(one):
            if not one or not one.next:
                return one
            three = one.next.next
            one.next.next = one
            two = one.next
            one.next = helper(three)
            return two
        return helper(head)

나의 풀이2(반복)

# 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]:
        if not head or not head.next:
            return head

        dummy = ListNode(0)
        dummy.next = head

        prev, curr, nxt = dummy, head, head.next

        while nxt:
            prev.next, nxt.next, prev, curr = nxt, curr, curr, nxt.next
            if curr:
                nxt = curr.next
            else:
                prev.next = None
                break
        if curr: # odd case
            prev.next = curr
        
        return dummy.next

다른 풀이1(재귀)

# 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, one: Optional[ListNode]) -> Optional[ListNode]:
        if one and one.next:
            two = one.next
            one.next = self.swapPairs(two.next)
            two.next = one
            return two
        return one

다른 풀이2(반복)

# 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]:
        prev = ListNode(0)
        prev.next = head
        result = prev

        while head and head.next:
            curr = head.next
            head.next = curr.next
            curr.next = head
            prev.next = curr
            head = head.next
            prev = prev.next.next
        
        return result.next

책 풀이랑 비슷하게 풀긴 했지만, 가독성이나 디테일이 차이가 있다.
그래도 재귀 풀이를 책 안보고 풀었다!

profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글