새오의 개발 기록

Leetcode: 24 페어의 노드 스왑 본문

Algorithm/Leetcode

Leetcode: 24 페어의 노드 스왑

새오: 2022. 10. 19. 05:50

 

연결 리스트를 입력받아 페어 단위로 스왑하라



 

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

# 입력 예제
1->2->3->4

# 출력 예제
2->1->4->3

 

 

 

 

풀이

 

1. 반복

def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:

        dummy = ListNode(0, head)
        print(dummy)
        prev, curr = dummy, head
        
        while curr and curr.next:
            next_pair = curr.next.next
            second = curr.next
            
            second.next = curr
            curr.next = next_pair
            prev.next = second
            
            prev = curr
            curr = next_pair
            
        return dummy.next

 

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode 238: 자신을 제외한 배열의 곱  (0) 2022.10.07
Leetcode 561: 배열 파티션 1  (0) 2022.10.06
Leetcode 1: 두 수의 합  (0) 2022.10.03
Leetcode 49: 그룹 애너그램  (0) 2022.10.02
Leetcode 819: 가장 흔한 단어  (0) 2022.10.01