method: linked list
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
prev = dummy = ListNode(0)
dummy.next = head
curr = prev.next
while curr and curr.next:
next = curr.next
curr.next = next.next
next.next = prev.next
prev.next = next
prev = prev.next.next
curr = curr.next
if curr == None: # edge cases, if there is one or two nodes
next = None
else:
next = curr.next
return dummy.next