# 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:
return None
arr = []
cur = head
while cur:
arr.append(cur)
cur = cur.next
for i in range(0, len(arr) - 1, 2):
arr[i], arr[i + 1] = arr[i + 1], arr[i]
for i in range(len(arr) - 1):
arr[i].next = arr[i + 1]
arr[-1].next = None
return arr[0]# 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
cur = head
nxt = head.next
cur.next = self.swapPairs(nxt.next)
nxt.next = cur
return nxt# 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]:
dummy = ListNode(0, head)
prev, curr = dummy, head
while curr and curr.next:
nxtPair = curr.next.next
second = curr.next
# Reverse this pair
second.next = curr
curr.next = nxtPair
prev.next = second
# Update pointers
prev = curr
curr = nxtPair
return dummy.next