본문 바로가기
Programming/LeetCode

[LeetCode] Swap Nodes in Pairs

by 데이터현 2022. 3. 24.

https://leetcode.com/problems/swap-nodes-in-pairs/

 

Swap Nodes in Pairs - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

짝을 이뤄서 노드를 변경하는 것 value 값을 변경하면 안된다.

1 <-> 2 까지는 괜찮은데

3 <-> 4 를 변경할때 1의 next가 3이 아닌 4가 되어야 해서 이 부분에서 신경을 써줘야 함.

 

 

반복문을 이용한 풀이

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        root = prev = ListNode(None)
        prev.next = head
        while head and head.next:
            b = head.next
            head.next = b.next
            b.next = head
            
            prev.next = b
            
            head = head.next
            prev = prev.next.next
        return root.next

 

재귀를 이용한 풀이

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        while head and head.next:
            p = head.next
            head.next = self.swapPairs(p.next)
            p.next = head
            return p
        return head

 

'Programming > LeetCode' 카테고리의 다른 글

[LeetCode] Two City Scheduling  (0) 2022.03.25
[LeetCode] Valid Parentheses  (0) 2022.03.25
[LeetCode] Boats to Save People  (0) 2022.03.24
[LeetCode] Add Two Numbers  (0) 2022.03.23
[LeetCode] Reverse Linked List  (0) 2022.03.23

댓글