[파이썬 알고리즘 인터뷰] 17번 : 페어의 노드 스왑

Dong·2022년 9월 27일

알고리즘

목록 보기
5/6

문제

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

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

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

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Input: head = [1]
Output: [1]

풀이

재귀를 이용해서 리스트 노드 2개씩 보면서 두 개를 바꾸어주었다.

class Solution:

    def swap(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head

        first, second = head, head.next
        first.next, second.next = second.next, first

        first.next = self.swap(first.next)
        
        return second



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

이번에는 책 풀이랑 비슷하게 풀어 깔끔하게 잘 푼것 같다.

profile
Hello ~

0개의 댓글