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