5/09/2020

[LeetCode] 24. Swap Nodes in Pairs

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

Swap nodes in pairs recursively.

Time Complexity : O ( N ) ,  N = length of list
Space Complexity: O ( 1 ),  swap in space.

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        
        if head and head.next:
            tmp = head.next.next
        
            left, right = head, head.next
            
            right.next = left
            left.next = self.swapPairs(tmp)
            
            return right
        
        return head

No comments:

Post a Comment