class ListNode():
def __init__(self, x):
self.val = x
self.next = None
class Solution():
def swapPairs(self, x):
cur = dummy = ListNode(0)
tmp, step = None, 1
while x:
if step % 2:
tmp = ListNode(x.val)
else:
cur.next, cur.next.next = ListNode(x.val), tmp
cur, tmp = cur.next.next, None
x, step = x.next, step + 1
if tmp:
cur.next = tmp
return dummy.next
if __name__ == "__main__":
x, x.next, x.next.next, x.next.next.next = ListNode(1), ListNode(2), ListNode(3), ListNode(4)
res = Solution().swapPairs(x)
assert '{0}->{1}->{2}->{3}'.format(res.val, res.next.val, res.next.next.val, res.next.next.next.val) \
== '2->1->4->3'