Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)
prev
, first_node
, and second_node
to help in swapping the pairs.next
of prev
to second_node
.next
of first_node
to second_node.next
.next
of second_node
to first_node
.prev
two steps forward (to first_node
).first_node
two steps forward (to the next pair’s first node).next
of the dummy node as the new head.class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def swapPairs(head: ListNode) -> ListNode:
# Create a dummy node to simplify edge cases.
dummy = ListNode(0)
dummy.next = head
prev = dummy
while head and head.next:
# Nodes to be swapped
first_node = head
second_node = head.next
# Swapping
prev.next = second_node
first_node.next = second_node.next
second_node.next = first_node
# Reinitializing the pointers for next swap
prev = first_node
head = first_node.next
# Return the new head node
return dummy.next
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?