코드

Swap Nodes in Pairs

ehei 2019. 10. 24. 00:22

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

인접한 두 개의 노드를 서로 바꾸는 문제
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head is None:
            return head
        
        nextHead = head.next
        
        if nextHead is None:
            return head
        
        nextNextHead = nextHead.next
        nextHead.next = head
        
        if nextNextHead is None:
            head.next = None
        else:
            head.next = self.swapPairs( nextNextHead )
            
        return nextHead