-1

I'm trying to solve leetcode question 24: Swap Nodes in Pairs. The description of the problem is as follow:

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

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

My code is as follow:

class Solution(object):
    def swapPairs(self, head):
        if not head or not head.next:
            return head
        
        curr = head    
        curr_adj = curr.next 

        while curr and curr.next:
            
            # Saving the next Pair
            next_pair = curr.next.next # Here im saving the next pair (i.e., the value 3)

            # Swaping the nodes
            curr_adj.next = curr   # pointing 2 --> 1
            curr.next = next_pair  # pointing 1 --> 3
                                   # so I assume I would have 2-->1-->3-->4

            # update the ptrs 
            curr = next_pair       # now curr should be 3
            curr_adj = curr.next   # curr_adj should be 4
        
        return head

# at the next iteration, I assume 4 --> 3 --> Null 
# So finally, I should have 2-->1-->4-->1--> Null

I am getting the following error. What am I doing wrong?

AttributeError: 'NoneType' object has no attribute 'next'
    curr_adj = curr.next
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    The error means that you are trying to access an attribute "next" of an object, but the object is `None` (and thus the type of the object is `NoneType`, which does not have a `next` attribute. In your concrete case, you need to handle the case where `curr` becomes `None` in your loop. Accessing `curr.next` is invalid if `curr` is `None`. – Cedric Jan 16 '23 at 09:39

1 Answers1

0

Observe this line:

next_pair = curr.next.next

From your loop condition, it is possible for curr.next.next to be None. This evaluates to next_pair = None.

Then, you assign curr = next_pair. The error surfaces when you attempt to access the next attribute of curr, curr_adj = curr.next, which does not exist.

Why not consider a recursive approach?

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None or head.next is None:
            return head
        n1, n2 = head, head.next
        n1.next, n2.next = self.swapPairs(n2.next), n1
        return n2
Ci Leong
  • 92
  • 11