class Solution:
# @param a ListNode
# @return a ListNode
def swapPairs(self, head):
p1 = guard = ListNode(0)
guard.next = head
try:
while True:
p0, p1, p2 = p1, p1.next, p1.next.next
p0.next, p1.next, p2.next = p2, p2.next, p1
except:
return guard.next
My accepted solution in Python, quite fast

An updated version based on yours that I personally think is more straightfoward
# Definition for singlylinked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param a ListNode # @return a ListNode def swapPairs(self, head): if not head: return None dummyNode = p0 = ListNode(0) dummyNode.next = head while p0.next and p0.next.next: p1, p2 = p0.next, p0.next.next p0.next, p1.next, p2.next = p2, p2.next, p1 p0 = p0.next.next return dummyNode.next

if not head: return
this can be removed to make it even cleaner.class Solution: # @param {ListNode} head # @return {ListNode} def swapPairs(self, head): dummy = cur = ListNode(1) dummy.next = head while cur.next and cur.next.next: p1, p2 = cur.next, cur.next.next cur.next, p1.next, p2.next = p2, p2.next, p1 cur = cur.next.next return dummy.next