# 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
"""
dummy = ListNode()
dummy.next = head
curr = head
last_node = dummy
while curr != None and curr.next != None:
curr_next = curr.next
last_node.next = curr.next
curr.next = curr_next.next
curr_next.next = curr
last_node = curr
curr = curr.next
dummy = dummy.next
return dummy
This is my first time solution when I approach to this question. As normal, create a dummy node linked to the head, which helps with the declaring the last_node variable. And also declare the variable curr that equal to head.
Then for the condition of the while loop, we need to ensure the curr node is not None, to prevent for example, if head = None, curr.next will raise an AttributeError, also, when let say there are totally two nodes in a linkedlist, after swapping, curr would equal to curr.next which is also None, and it could raise an AttributeError. Verify curr.next not equal to None because there is no more node to swap if this condition met.
for the code in while loop, it is basically doing the things as follow:
the number beside the line is line of the instrucution within the while loop.
finally, after the while loop, remove the dummy node and return dummy.